从文档来看,还不清楚。在Java中,你可以像这样使用split方法:

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

当前回答

struct String有一个特殊的split方法:

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"]);

按字符串分割:

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

按闭包分割:

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

其他回答

struct String有一个特殊的split方法:

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"]);

按字符串分割:

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

按闭包分割:

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

使用分割()

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();

如果您正在寻找python风格的拆分,即对拆分字符串的两端进行元组解包,您可以这样做

if let Some((a, b)) = line.split_once(' ') {
    // ...
}

split返回一个迭代器,你可以使用collect: split_line.collect::<Vec<_>>()将其转换为Vec。遍历迭代器而不是直接返回Vec有几个优点:

split is lazy. This means that it won't really split the line until you need it. That way it won't waste time splitting the whole string if you only need the first few values: split_line.take(2).collect::<Vec<_>>(), or even if you need only the first value that can be converted to an integer: split_line.filter_map(|x| x.parse::<i32>().ok()).next(). This last example won't waste time attempting to process the "23.0" but will stop processing immediately once it finds the "1". split makes no assumption on the way you want to store the result. You can use a Vec, but you can also use anything that implements FromIterator<&str>, for example a LinkedList or a VecDeque, or any custom type that implements FromIterator<&str>.

还有split_whitespace()

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