在 Rust 中反转字符串 [英] Reversing a string in Rust

查看:98
本文介绍了在 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

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

What is the correct way to do this?

推荐答案

第一个也是最基本的问题是这不是反转 Unicode 字符串的方式.您正在反转代码点的顺序,您希望在其中反转 graphemes 的顺序.可能还有其他我不知道的问题.文字很难.

The first, and most fundamental, problem is that this isn't how you reverse a Unicode string. You are reversing the order of the code points, where you want to reverse the order of graphemes. There may be other issues with this that I'm not aware of. Text is hard.

编译器指出了第二个问题:您试图将字符串文字与 char 迭代器进行比较.charsrev 不会产生新的字符串,它们会产生惰性序列,就像一般的迭代器一样.以下作品:

The second issue is pointed out by the compiler: you are trying to compare a string literal to a char iterator. chars and rev don't produce new strings, they produce lazy sequences, as with iterators in general. 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()
        // 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).

Note that graphemes used to be in the standard library as an unstable method, so the above will break with sufficiently old versions of Rust. In that case, you need to use UnicodeSegmentation::graphemes(s, true) instead.

这篇关于在 Rust 中反转字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆