弦的反向单词
处理字符串后,我正在尝试在单词之间显示空间,但是我得到了
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");
}
I'm trying to show spaces between the words after processing the string but I'm getting
thread 'main' panicked at 'assertion failed: `(left == right)`
left: `"abcd"`,
right: `"a b c d"`', src/main.rs:11:5
How can I fix it?
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");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您将输入分配在Whitespace上,但是当您收集它时,它会在没有任何分离器的情况下加入。要修复,您可以将其收集到
vec< string>
上,然后在其上调用.join(“”)
:;不是分配中间的VEC:
You split the input on whitespace but when you collect it, it's joined without any separator. To fix, you can collect it into a
Vec<String>
and then call.join(" ")
on it:Playground
A more efficient implementation of
reverse_words
that does not allocate an intermediate Vec:Playground