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.
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.
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.
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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With