string - 仅使用 for 循环体内的条件将字符串与空格连接起来

标签 string loops rust string-concatenation

我在做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/

相关文章:

python - 查找 python 中 t 测试用例的除数总数

rust - 如何解析包含简单列表和键值列表(关联数组)的YAML

asp.net - 带按钮的私有(private)字符串的 ViewState

c++ - 给出奇怪值的字符串

python - for 循环不迭代文件

javascript - 使用 setTimeout 操作通过循环生成的新 DOM 元素

algorithm - 迭代BTreeSet和HashSet的时间复杂度是多少?

types - 创建一个基本上是 String 但与 String 不兼容的类型?

java - 格式化字符串数组以反转字符串

objective-c - 如何在代码中接收 slider 的当前值?