我希望能够在字符串aabbaacaaaccaaa
上分开字符串bb
,cc
但不能在b
或上分开c
。该示例将导致aa,aacaaa,aaa
。
我已经可以在一个单一的分隔符分割字符串,字()函数把一个字符串,
\n
并且\t
,所以我想它一定是可行的。
不幸的是,您现在无法使用标准库执行此操作。但是,您可以拆分多个char
定界符,就像words
这样。您需要给split
:
for part in "a,bc;d".split(&[',', ';'][..]) {
println!(">{}<", part);
}
但是,如果尝试使用字符串,则会出现此错误:
error: the trait `core::str::pattern::Pattern<'_>` is not implemented for the type `&[&str]` [E0277]
for part in "a,bc;d".split(&[",", ";"][..]) {
^~~~~~~~~~~~~~~~~~~~~~
但是,您可以Pattern
为自己的类型实现,其中包括一片字符串。
如果您喜欢使用标准库中不包含的功能强大的板条箱,则可以使用regex:
extern crate regex;
fn main() {
let re = regex::Regex::new(r"bb|cc").unwrap();
for part in re.split("aabbaacaaaccaaa") {
println!(">{}<", part);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句