如何通过分割中间有空格的字符串来返回字符串向量
fn line_to_words(line: &str) -> Vec<String> {
line.split_whitespace().collect()
}
fn main() {
println!( "{:?}", line_to_words( "string with spaces in between" ) );
}
上面的代码返回这个错误
line.split_whitespace().collect()
| ^^^^^^^ value of type `std::vec::Vec<std::string::String>` cannot be built from `std::iter::Iterator<Item=&str>`
|
= help: the trait `std::iter::FromIterator<&str>` is not implemented for `std::vec::Vec<std::string::String>`
如果你想返回Vec<String>
你需要转换Iterator<Item=&str>
你从split_whitespace
进入一个Iterator<Item=String>
。转换迭代器类型的一种方法是使用Iterator::map
。
要转换的函数&str
to String
is str::to_string
。把这些放在一起给你
fn line_to_words(line: &str) -> Vec<String> {
line.split_whitespace().map(str::to_string).collect()
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)