string - 替换字符串中第一次出现的模式

标签 string rust

我正在尝试编写一个 replace_first() 函数,但我找不到管理它的正确方法。

我有以下输入:

let input = "Life is Life".to_string();

我想将此类输入替换为以下浪漫输出:

My wife is Life

replace 函数替换所有出现的地方。我如何实现 replace_first 函数,以便我可以像下面这样使用它:

let input = "Life is Life".to_string();
let output = input.replace_first("Life", "My wife");
println!({}, output); // Expecting the output as "My wife is life"

最佳答案

使用replacen

Replaces first N matches of a pattern with another string.

replacen creates a new String, and copies the data from this string slice into it. While doing so, it attempts to find matches of a pattern. If it finds any, it replaces them with the replacement string slice at most count times.

let input = "Life is Life".to_string();
let output = input.replacen("Life", "My wife", 1);

assert_eq!("My wife is Life", output);

Rust Playground

关于string - 替换字符串中第一次出现的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54419435/

相关文章:

java - 如何在 Java 中递增/递减一个 unicode 字符串?

rust - 限制 Rust 程序中的 cpurate

rust - 如何使用hyper添加多个RPC端点?

Rust 中作为可选函数参数的闭包

ios - 检查 NSString 中的平衡括号时忽略表情符号

Python:组合字符串和列表

string - 删除Excel单元格中的重复项

string - 将 int 转换为字符串向量

json - 如何在具有可变键名的 json 对象上使用 serde json

java - 将十进制数转换为其补码的输出