从文档来看,还不清楚。在Java中,你可以像这样使用split方法:
"some string 123 ffd".split("123");
从文档来看,还不清楚。在Java中,你可以像这样使用split方法:
"some string 123 ffd".split("123");
当前回答
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>.
其他回答
有三种简单的方法:
分隔符: S.split ("separator") | S.split ('/') | S.split (char::is_numeric) 空格: s.split_whitespace () 换行: s.lines () 通过regex:(使用regex crate) Regex::新(r \ s) .unwrap()。分开(“一二三”)
每种类型的结果都是一个迭代器:
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());
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"]);
如果您正在寻找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"]
}