在Rust中反转一个字符串

时间:2015-01-17 05:21:05

标签: rust

这有什么问题:

fn main() {
    let word: &str = "lowks";
    assert_eq!(word.chars().rev(), "skwol");
}

我收到这样的错误:

error[E0369]: binary operation `==` cannot be applied to type `std::iter::Rev<std::str::Chars<'_>>`
 --> src/main.rs:4:5
  |
4 |     assert_eq!(word.chars().rev(), "skwol");
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: an implementation of `std::cmp::PartialEq` might be missing for `std::iter::Rev<std::str::Chars<'_>>`
  = note: this error originates in a macro outside of the current crate

这样做的正确方法是什么?

2 个答案:

答案 0 :(得分:30)

因为,@ DK。建议.graphemes()&str稳定版中不可用,您也可以按照@huon在评论中建议的那样做:

fn main() {
    let foo = "palimpsest";
    println!("{}", foo.chars().rev().collect::<String>());
}

答案 1 :(得分:21)

第一个也是最基本的问题是,这不是你如何反转Unicode字符串。您正在颠倒代码点的顺序,您要在其中颠倒 graphemes 的顺序。我可能还有其他问题,我不知道。文字很难。

编译器指出了第二个问题:您正在尝试将字符串文字与char迭代器进行比较。 charsrev不会产生新的字符串,它们会生成惰性序列,就像通常的迭代器一样。 The following works

/*!
Add the following to your `Cargo.toml`:

```cargo
[dependencies]
unicode-segmentation = "0.1.2"
```
*/
extern crate unicode_segmentation;
use unicode_segmentation::UnicodeSegmentation;

fn main() {
    let word: &str = "loẅks";
    let drow: String = word
        // Split the string into an Iterator of &strs, where each element is an
        // extended grapheme cluster.
        .graphemes(true)
        // Reverse the order of the grapheme iterator.
        .rev()
        // flat_map takes each element of an iterator, turns that element into
        // a new iterator, then outputs the elements of these sub-iterators as
        // one long chain.  In this case, we're turning each grapheme cluster
        // into an Iterator of code points, then yielding all those code points.
        // That is, this is now an Iterator of chars from the reversed grapheme
        // clusters.
        .flat_map(|g| g.chars())
        // Collect all the chars into a new owned String.
        .collect();

    assert_eq!(drow, "skẅol");

    // Print it out to be sure.
    println!("drow = `{}`", drow);
}

请注意,graphemes曾经作为一种不稳定的方法出现在标准库中,所以上面的内容会破坏足够旧版本的Rust。在这种情况下,您需要改为使用UnicodeSegmentation::graphemes(s, true)