如何在恒定时间内替换字符串中的单个字符并且不使用额外空间? [英] How do I replace a single character in a string in constant time and using no additional space?

查看:25
本文介绍了如何在恒定时间内替换字符串中的单个字符并且不使用额外空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不是确切的用例,但基本上是我想要做的:

This isn't the exact use case, but it is basically what I am trying to do:

let mut username = "John_Smith";
println!("original username: {}",username);
username.set_char_at(4,'.'); // <------------- The part I don't know how to do
println!("new username: {}",username);

我不知道如何在恒定时间内做到这一点并且不使用额外的空间.我知道我可以使用替换",但替换是 O(n).我可以制作字符的向量,但这需要额外的空间.

I can't figure out how to do this in constant time and using no additional space. I know I could use "replace" but replace is O(n). I could make a vector of the characters but that would require additional space.

我认为您可以使用诸如 as_mut_slice 之类的东西创建另一个指针变量,但这被认为是不安全的.有没有一种安全的方法可以在恒定的时间和空间中替换字符串中的字符?

I think you could create another variable that is a pointer using something like as_mut_slice, but this is deemed unsafe. Is there a safe way to replace a character in a string in constant time and space?

推荐答案

如果您只想处理 ASCII,则有单独的类型:

If you want to handle only ASCII there is separate type for that:

use std::ascii::{AsciiCast, OwnedAsciiCast};

fn main() {
    let mut ascii = "ascii string".to_string().into_ascii();
    *ascii.get_mut(6) = 'S'.to_ascii();
    println!("result = {}", ascii);
}

有一些缺失的部分(例如 &strinto_ascii),但它可以满足您的需求.如果输入字符串无效 asciito_/into_ascii 的当前实现将失败.有 to_ascii_opt(可能失败的方法的旧命名),但将来可能会重命名为 to_ascii(并删除或重命名失败的方法).

There are some missing pieces (like into_ascii for &str) but it does what you want. Current implementaion of to_/into_ascii fails if input string is invalid ascii. There is to_ascii_opt (old naming of methods that might fail) but will probably be renamed to to_ascii in the future (and failing method removed or renamed).

这篇关于如何在恒定时间内替换字符串中的单个字符并且不使用额外空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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