string - 如何更改 rust 字符串中特定索引处的字符?
问题描述
我正在尝试更改字符串中特定索引处的单个字符,但我不知道如何生锈。例如,我如何将“hello world”中的第 4 个字符更改为“x”,这样它就变成了“helxo world”?
解决方案
最简单的方法是使用这样的replace_range()
方法:
let mut hello = String::from("hello world");
hello.replace_range(3..4,"x");
println!("hello: {}", hello);
输出hello: helxo world
:(游乐场)
请注意,如果要替换的范围不在 UTF-8 代码点边界上开始和结束,则会出现恐慌。例如这会恐慌:
let mut hello2 = String::from("hell world");
hello2.replace_range(4..5,"x"); // panics because needs more than one byte in UTF-8
如果要替换第 n 个 UTF-8 代码点,则必须执行以下操作:
pub fn main() {
let mut hello = String::from("hell world");
hello.replace_range(
hello
.char_indices()
.nth(4)
.map(|(pos, ch)| (pos..pos + ch.len_utf8()))
.unwrap(),
"x",
);
println!("hello: {}", hello);
}
(游乐场)
推荐阅读
- c# - 我如何将 MQTT 从字符串解析为在 c#/unity 中浮动?
- unity3d - 制作双面平面
- python - Pandas pivot_table 日期时间排序错误
- php - 当用户尝试验证他们的电子邮件 Laravel **ErrorException (E_NOTICE) Undefined variable: gs**
- python - 如何在熊猫中用另一个值列值?
- tfs - 如何解决错误“system.security.principal.windowsidentity - 主域和可信域之间的真实关系失败”?
- caching - 错误:无法执行缓存操作(缓存已停止),服务空闲数小时后
- javascript - 在显示的特定选项卡上触发事件
- r - 我可以使用 R 中另一个数据帧的相应值来划分数据帧的每一列吗?
- postgresql - 使用 PostgreSQL 根据特定列和优先级删除数据