英文:
Map the split to trim each entry
问题
I need to write a function that takes a string as an input, splits it by the line break character and trims all the redundant break characters in each entry of the split. I've come up with the following:
fn split_and_trim(text: &String) {
let lines = text.split('\n').map(|l| String::from(l).trim());
println!("{:?}", lines)
}
But this code returns me the following error:
6 | let lines = text.map(|l| String::from(l).trim());
| ---------------^^^^^^^
| |
| returns a reference to data owned by the current function
| temporary value created here
Trying to rewrite it the following way:
let lines: Vec<String> = text.split('\n').map(|l| String::from(l).trim()).collect();
Returns another error:
value of type `Vec<String>` cannot be built from `std::iter::Iterator<Item=&str>`
What would be the correct way of achieving this goal (splitting the string and trimming each element)? Thanks in advance!
英文:
I need to write a function that takes a string as an input, splits it by the line break character and trims all the redundant break characters in each entry of the split. I've come up with the following:
fn split_and_trim(text: &String) {
let lines - text.split('\n').map(|l| String::from(l).trim());
println!("{:?}", lines)
}
But this code returns me the following error:
6 | let lines = text.map(|l| String::from(l).trim());
| ---------------^^^^^^^
| |
| returns a reference to data owned by the current function
| temporary value created here
Trying to rewrite it the following way:
let lines: Vec<String> = text.split('\n').map(|l| String::from(l).trim()).collect();
Returns another error:
value of type `Vec<String>` cannot be built from `std::iter::Iterator<Item=&str>`
What would be the correct way of achieving this goal (splitting the string and trimming the each element)? Thanks in advance!
答案1
得分: 2
You don't need to create new String
s here, since trim
only needs slices.
fn split_and_trim(text: &str) {
let lines: Vec<&str> = text.split('\n').map(|l| l.trim()).collect();
println!("{:?}", lines)
}
You should also take &str
instead of &String
as a function parameter in almost all cases.
If you need String
s, you can convert them after trimming.
英文:
You don't need to create new String
s here, since trim
only needs slices. (playground)
fn split_and_trim(text: &str) {
let lines: Vec<&str> = text.split('\n').map(|l| l.trim()).collect();
println!("{:?}", lines)
}
You should also take &str
instead of &String
as a function parameter in almost all cases.
If you need String
s, you can convert them after trimming.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论