我在做Rust Koans我被困在这个问题上:
#[test]
fn for_loops_two() {
let words: [&'static str; 3] = ["I", "love", "Rust"];
let space: &str = " ";
let mut sentence: String = String::new();
for word in words.iter() {
// __
}
println!("{:?}", sentence);
assert!(sentence == "I love Rust".to_string());
}
我知道我需要连接字符串,但这会失败:
#[test]
fn for_loops_two() {
let words: [&'static str; 3] = ["I", "love", "Rust"];
let mut sentence: String = String::new();
for word in words.iter() {
sentence.push_str(word);
}
println!("{:?}", sentence); // "ILoveRust"
assert!(sentence == "I love Rust".to_string());
}
我可以在每次迭代后添加一个空格:
#[test]
fn for_loops_two() {
let words: [&'static str; 3] = ["I", "love", "Rust"];
let space: &str = " ";
let mut sentence: String = String::new();
for word in words.iter() {
sentence.push_str(word);
sentence.push_str(space);
}
println!("{:?}", sentence); // "I Love Rust "
assert!(sentence == "I love Rust".to_string());
}
这也会失败,因为最后一次迭代会添加一个空格。
如果我们在最后一次迭代,我想我可以写一个条件,但我正在努力使语法正确。此外,我觉得所有这些都有更好的解决方案,但我只是想不出语法。
我怎样才能使上面的断言在循环中通过条件传递而不在最后一次迭代中添加空格?
最佳答案
有点晚了,但这是一个只修改循环内 block 的解决方案:
#[test]
fn for_loops_two() {
let words: [&'static str; 3] = ["I", "love", "Rust"];
let mut sentence: String = String::new();
for word in words.iter() {
if sentence != "".to_string() {
sentence.push(' ')
}
sentence.push_str(word)
}
println!("{:?}", sentence);
assert!(sentence == "I love Rust".to_string());
}
关于string - 仅使用 for 循环体内的条件将字符串与空格连接起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55320038/