Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I split a string (String or &str) on more than one delimiter?

Tags:

string

split

rust

I want to be able to separate the string aabbaacaaaccaaa on the strings bb and cc but not on b or c. The example would result in aa,aacaaa,aaa.

I already can split a string on a single delimiter, and the words() function splits a string on ,\n and \t, so I figured it must be possible.

like image 834
awesomefireduck Avatar asked Mar 24 '15 18:03

awesomefireduck


People also ask

How can I split a string?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How do I split a string into multiple strings?

split() The method split() splits a String into multiple Strings given the delimiter that separates them. The returned object is an array which contains the split Strings. We can also pass a limit to the number of elements in the returned array.

Can you use split on a string?

Split is used to break a delimited string into substrings. You can use either a character array or a string array to specify zero or more delimiting characters or strings. If no delimiting characters are specified, the string is split at white-space characters.


1 Answers

Unfortunately, you can't do this with the standard library right now. You can split on multiple char delimiters though, as words does. You need to give a slice of characters to split:

for part in "a,bc;d".split(&[',', ';'][..]) {
    println!(">{}<", part);
}

If you try with strings, however:

for part in "a,bc;d".split(&[",", ";"][..]) {
    println!(">{}<", part);
}

You'll get the error:

error[E0277]: expected a `Fn<(char,)>` closure, found `[&str]`
 --> src/main.rs:2:32
  |
2 |     for part in "a,bc;d".split(&[",", ";"][..]) {
  |                                ^^^^^^^^^^^^^^^ expected an `Fn<(char,)>` closure, found `[&str]`
  |
  = help: the trait `Fn<(char,)>` is not implemented for `[&str]`
  = note: required because of the requirements on the impl of `FnOnce<(char,)>` for `&[&str]`
  = note: required because of the requirements on the impl of `Pattern<'_>` for `&[&str]`

In nightly Rust, you could implement Pattern for your own type that includes a slice of strings.

If you are cool with using a well-supported crate that isn't part of the standard library, you can use regex:

use regex; // 1.4.5

fn main() {
    let re = regex::Regex::new(r"bb|cc").unwrap();
    for part in re.split("aabbaacaaaccaaa") {
        println!(">{}<", part);
    }
}
like image 122
Shepmaster Avatar answered Oct 10 '22 15:10

Shepmaster