rust - 在 Rust 中反转字符串

标签 rust

我想在 Rust 中做一个简单的字符串反转,但我似乎无法弄清楚要使用什么函数来做到这一点。

假设我有一个字符串:____x_xx__x

反转这个字符串将变成:xxxx_x__xx_

我试过:

//res is the string I want to invert
for mut c in res.as_slice().chars() {
  c =
    match c {
      'x' => '_',
       _  => 'x'
    };
};

但这警告我永远不会读取值 c,所以我猜我使用的 c 实际上不是对切片中字符的引用?

最佳答案

fn main() {
    let mut res = String::from_str("____x_xx__x").into_ascii();

    for c in res.mut_iter() {
        *c = match c.to_char() {
            'x' => '_',
             _  => 'x'
        }.to_ascii();
    };

    println!("{}", res.into_string());
}

play.rust-lang.org

关于rust - 在 Rust 中反转字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24877699/

相关文章:

generics - 为什么在使用嵌套泛型创建枚举时会出现 "overflowed on"错误?

rust - 如何将受特征限制的类型传递给Serde的deserialize_with?

qml - 为 QMLRS 编译示例时为 "QtQuick.Controls version 1.2 is not installed"

process - 执行任何 bash 命令,立即获取 stdout/stderr 的结果并使用 stdin

performance - Rust 在解析文件时比 Python 慢

rust - 如何编辑 Cargo.toml 以便将资源文件包含在我的 Cargo 包中?

rust - Rust-混合使用默认宏和个人默认实现

rust - 在不安全的 rust 中通过 *mut T 来突变 &T 是 UB 吗?

rust - 从 Rust 填充 C 字符串指针的正确方法是什么?

struct - 如何创建嵌套结构?