How can I extract a string prefix that comes before a given character?

Viewed 496

Is there a way of extracting a prefix defined by a character without using split? For instance, given "some-text|more-text" how can I extract "some-text" which is the string that comes before "|"?

2 Answers

If your issue with split is that it may also split rest of the string, then consider str.splitn(2, '|') which splits into maximum two parts, so you get the string up to the first | and then the rest of the string even if it contains other | characters.

Split may be the best way. But, if for whatever reason you want to do it without .split(), here's a couple alternatives.

You can use the .chars() iterator, chained with .take_while(), then produce a String with .collect().

// pfx will be "foo".
let pfx = "foo|bar".chars()
                   .take_while(|&ch| ch != '|')
                   .collect::<String>();

Another way, which is pretty efficient, but fallable, is to create a slice of the original str:

let s   = "foo|bar";
let pfx = &s[..s.find('|').unwrap()];

// or - if used in a function/closure that returns an `Option`.
let pfx = &s[..s.find('|')?];

Related