Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 如何更新字符串中的字符?_String_Rust - Fatal编程技术网

String 如何更新字符串中的字符?

String 如何更新字符串中的字符?,string,rust,String,Rust,我正在尝试更新字符串中的字符,但似乎无法做到这一点 fn main() { let mut s = "poyo".to_string(); // s[1] = 'i'; or s.get_mut(1) = 'i'; can't do either println!("{}", s); // expecting "piyo" } 我知道为什么会发生这种情况(String没有实现IndexMut),但我不知道如何解决这个问题 答案取决于您处理的字符串的种类;如果您仅使用AS

我正在尝试更新
字符串中的
字符
,但似乎无法做到这一点

fn main() {
    let mut s = "poyo".to_string();
    // s[1] = 'i'; or s.get_mut(1) = 'i'; can't do either
    println!("{}", s); // expecting "piyo"
}
我知道为什么会发生这种情况(
String
没有实现
IndexMut
),但我不知道如何解决这个问题


答案取决于您处理的
字符串的种类;如果您仅使用ASCII(这意味着每个字符的大小都是一个字节,您可以直接操作底层的
Vec
),您可以执行以下操作:

fn main() {
    let mut s = "poyo".to_string();
    let mut bytes = s.into_bytes();
    bytes[1] = 'i' as u8;

    unsafe { s = String::from_utf8_unchecked(bytes) }

    println!("{}", s);
}
或:

但是,如果您(可能)使用多字节字符(这就是
String
没有实现
IndexMut
甚至
Index
),安全的方法是使用迭代器,遍历它,并基于其元素创建一个新的
String

fn main() {
    let s = "poyo".to_string();
    let iter = s.chars();
    let mut new = String::new();

    for (i, mut c) in iter.enumerate() {
        if i == 1 { c = 'i'; }
        new.push(c);
    }

    println!("{}", new);
}
fn main() {
    let s = "poyo".to_string();
    let iter = s.chars();
    let mut new = String::new();

    for (i, mut c) in iter.enumerate() {
        if i == 1 { c = 'i'; }
        new.push(c);
    }

    println!("{}", new);
}