gpt4 book ai didi

c# - 如何替换 .NET 中字符串的*第一个实例*?

转载 作者:IT王子 更新时间:2023-10-29 03:35:41 26 4
gpt4 key购买 nike

我想替换给定字符串中的第一个匹配项。

如何在 .NET 中完成此操作?

最佳答案

string ReplaceFirst(string text, string search, string replace)
{
int pos = text.IndexOf(search);
if (pos < 0)
{
return text;
}
return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
}

例子:

string str = "The brown brown fox jumps over the lazy dog";

str = ReplaceFirst(str, "brown", "quick");

编辑:作为@itsmatt mentioned ,还有 Regex.Replace(String, String, Int32),它可以做同样的事情,但在运行时可能更昂贵,因为它使用了一个功能齐全的解析器,我的方法在其中执行一个查找和三个字符串连接。

EDIT2:如果这是一项常见任务,您可能希望将该方法设为扩展方法:

public static class StringExtension
{
public static string ReplaceFirst(this string text, string search, string replace)
{
// ...same as above...
}
}

使用上面的例子现在可以写:

str = str.ReplaceFirst("brown", "quick");

关于c# - 如何替换 .NET 中字符串的*第一个实例*?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/141045/

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