gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:57:59 24 4
gpt4 key购买 nike

我正在尝试编写一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com