如何在Rust中分割string?

如何在Rust中分割一个string? 从它的文档中不清楚。 在Java中,我会这样做:

"some string 123 ffd".split("123"); 

使用split()

 let mut split = "some string 123 ffd".split("123"); 

这给了一个迭代器,你可以循环,或collect()到一个向量。

 for s in split { println!("{}", s) } let vec = split.collect::<Vec<&str>>(); // OR let vec: Vec<&str> = split.collect(); 

有一个特殊的方法split为结构String

 fn split<'a, P>(&'a self, pat: P) -> Split<'a, P> where P: Pattern<'a> 

按字符分割:

 let v: Vec<&str> = "Mary had a little lamb".split(' ').collect(); assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]); 

按string拆分:

 let v: Vec<&str> = "lion::tiger::leopard".split("::").collect(); assert_eq!(v, ["lion", "tiger", "leopard"]); 

按closures分割:

 let v: Vec<&str> = "abc1def2ghi".split(|c: char| c.is_numeric()).collect(); assert_eq!(v, ["abc", "def", "ghi"]); 

有三个简单的方法:

  1. 分隔符

     s.split("separator") 
  2. 空白

     s.split_whitespace() 
  3. 换行符

     s.lines() 

每种types的结果都是一个迭代器:

 let text = "foo\r\nbar\n\nbaz\n"; let mut lines = text.lines(); assert_eq!(Some("foo"), lines.next()); assert_eq!(Some("bar"), lines.next()); assert_eq!(Some(""), lines.next()); assert_eq!(Some("baz"), lines.next()); assert_eq!(None, lines.next()); 

还有split_whitespace()

 fn main() { let words: Vec<&str> = " foo bar\t\nbaz ".split_whitespace().collect(); println!("{:?}", words); // ["foo", "bar", "baz"] }