我试图将这个字符串转换为vec或类似于此的字符串表示.

"Text\n\0" ==> \"Text\" 0x0A 0x00

"Test1\t\x7FTest2" ==> \"Test1\" 0x09 0x7F \"Test2\"

有什么可能解决这个问题?

我试过了,这是rust playground link

fn main() {
    // let test = "Text\n\0";

    let str1 = "Test1\t\x7FTest2";
    let mut res = vec![];

    for c in str1.chars() {
        res.push("\"");
        if c == '\t' {        
            res.push("\" 0x09");
        } else if c == '\x7F' {
            res.push("\" 0x7F");
        } else {
            res.push(c);
        }
    }

    println!("{}", res.join(" "));
    assert_eq!(res.join(" "), "\"Test1\" 0x09 0x7F \"Test2\"".to_string());
}

推荐答案

try 以下,当找到一个特殊字符时,我们将其替换为十六进制表示形式,并将其他字符用引号括起来

  fn main() {
    let input = "Test1\t\x7FTest2";
    let mut res = String::new();
    let mut in_quotes = false;

    for c in input.chars() {
        match c {
            '\t' | '\n' | '\0' | '\x7F' => {
                if in_quotes {
                    res.push('"');
                    in_quotes = false;
                }
                if !res.is_empty() {
                    res.push(' ');
                }
                let code = match c {
                    '\t' => "0x09",
                    '\n' => "0x0A",
                    '\0' => "0x00",
                    _ => "0x7F",
                };
                res.push_str(code);
            }
            _ => {
                if !in_quotes {
                    if !res.is_empty() {
                        res.push(' ');
                    }
                    res.push('"');
                    in_quotes = true;
                }
                res.push(c);
            }
        }
    }

    if in_quotes {
        res.push('"');
    }

    println!("{}", res);
    assert_eq!(res, "\"Test1\" 0x09 0x7F \"Test2\"");
}

Rust相关问答推荐

为什么拥有的trait对象的相等运算符移动了正确的操作数?

如果A == B,则将Rc A下推到Rc B

通过解引用将值移出Box(以及它被脱糖到什么地方)?

在Rust中显式装箱受生存期限制的转换闭包

如何格式化传入Rust中mysql crate的Pool::new的字符串

如何编写一个以一个闭包为参数的函数,该函数以另一个闭包为参数?

可以为rust构建脚本编写单元测试吗?

我无法理解Rust范围的定义(Rust Programming Language,第二版克拉布尼克和尼科尔斯)

程序在频道RX上挂起

使用关联类型重写时特征的实现冲突

在 Rust 中,在需要引用 self 的 struct 体方法中使用闭包作为 while 循环条件

为什么切片时需要参考?

我可以在 Rust 中 serde struct camel_case 和 deserde PascalCase

如何连接 Rust 中的相邻切片

使用 HashMap 条目时如何避免字符串键的短暂克隆?

你能告诉我如何在 Rust 中使用定时器吗?

如果我不想运行析构函数,如何移出具有析构函数的 struct ?

从函数返回 u32 的数组/切片

火箭整流罩、tokio-scheduler 和 cron 的生命周期问题

为什么 Rust 中的关联类型需要明确的生命周期注释?