在Rust中反转一个字符串

Low*_*ong 21 rust

这有什么问题:

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

我收到这样的错误:

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
Run Code Online (Sandbox Code Playgroud)

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

bri*_*tar 42

因为,@DK.建议,在稳定版本中.graphemes()不可用&str,你可能只是做了@huon在评论中建议的内容:

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

  • 正如 DK. 的回答中提到的,**这可能是错误的**。例如,它[完全失败,显示“Åström”`](https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=0a246b78ace33fc66368f8c9e81320fb) (4认同)
  • @Shepmaster,看起来“Åström”在上面的游乐场链接中与“chars()”一起工作。至少我看到的输出是`m̈orts̊A`。不确定最近是否更新了稳定版以支持此功能。 (3认同)
  • @MilesF `Ås` 与 `s̊A` / `öm` 与 `m̈o` (2认同)

DK.*_*DK. 29

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

第二个问题由编译器指出:您正在尝试将字符串文字与char迭代器进行比较. chars并且rev不产生新的字符串,它们产生惰性序列,就像通常的迭代器一样. 以下作品:

/*!
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 = "low?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()
        // Collect all the chars into a new owned String.
        .collect();

    assert_eq!(drow, "skw?ol");

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

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

  • 我想你可以只是`.rev().collect()`,因为`String`实现了`FromIterator <&str>`.另外,fwiw,我认为*实际*最基本的问题是误解迭代器,字符串和类型一般(可理解,许多语言都不那么"迂腐"),而不是unicode正确性稍微细微点. (14认同)