字符串的倒序



我试图在处理字符串后显示单词之间的空格,但我得到

thread 'main' panicked at 'assertion failed: `(left == right)`
left: `"abcd"`,
right: `"a b c d"`', src/main.rs:11:5

我该如何修复它?

fn reverse_words(words: &str) -> String {
words.split_whitespace().map(reverse_word).collect()
}
fn reverse_word(word: &str) -> String {
word.chars().rev().collect();
}
fn main() {
assert_eq!(reverse_words("apple"), "elppa");
assert_eq!(reverse_words("a b c d"), "a b c d");
assert_eq!(reverse_words("double  spaced  words"), "elbuod  decaps  sdrow");
}

您使用空白分隔输入,但是当您收集它时,它将不使用任何分隔符连接起来。要解决这个问题,您可以将其收集到Vec<String>中,然后在其上调用.join(" "):

fn reverse_words(words: &str) -> String {
words.split_whitespace().map(reverse_word).collect::<Vec<_>>().join(" ")
}

游乐场


不分配中间Vec的更有效的reverse_words实现:

fn reverse_words(words: &str) -> String {
words
.split_whitespace()
.map(reverse_word)
.enumerate()
.fold(
String::new(),
|acc, (i, word)| if i == 0 { word } else { acc + " " + &word },
)
}

游乐场

fn reverse_words(words: &str) -> String {
words.to_string()
.split(" ")
.map(reverse_string)
.collect::<Vec<String>>()
.join(" ")
}
fn reverse_string(s: &str) -> String {
s.to_string()
.chars()
.rev()
.collect::<String>()
}