savx2
savx2

Reputation: 1071

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

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 "|"?

Upvotes: 5

Views: 3748

Answers (3)

Kornel
Kornel

Reputation: 100170

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.

There's also str.split_once('|') that returns None if | is not in the string.

Upvotes: 8

matan h
matan h

Reputation: 1162

as @Kornel point out, you can use the Split function:

let raw_text = "some-text|more-text";
let extracted_text = raw_text.split("|").next().unwrap();

 
<iframe src="https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&code=fn%20main()%20%7B%0A%20%20%20%20let%20raw_text%20%3D%20%22some-text%7Cmore-text%22%3B%0A%20%20%20%20let%20extracted_text%20%3D%20raw_text.split(%22%7C%22).next().unwrap()%3B%0A%20%20%20%20println!(%22%7B%7D%22%2Cextracted_text)%3B%0A%7D" style="width:100%; height:400px;"></iframe>

Upvotes: 1

Todd
Todd

Reputation: 5405

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('|')?];

Upvotes: 4

Related Questions