可能重复:
How do I replace the of a string in .NET?
假设我有一个字符串:
string s = "Hello world.";
如何将单词Hello
中的第一个o
替换为Foo
换句话说,我想以:
"HellFoo world."
我知道如何替换所有的o,但我只想替换第一个
发布于 2012-01-11 03:34:02
我认为您可以使用Regex.Replace的重载来指定要替换的最大次数...
var regex = new Regex(Regex.Escape("o"));
var newText = regex.Replace("Hello World", "Foo", 1);
发布于 2012-01-11 03:36:19
public 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);
}
下面是一个扩展方法,同样适用于每个VoidKing
请求
public static class StringExtensionMethods
{
public static string ReplaceFirst(this 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);
}
}
发布于 2012-01-11 03:32:27
有很多方法可以做到这一点,但最快的方法可能是使用IndexOf查找要替换的字母的索引位置,然后在要替换的字母之前和之后提取文本的子串。
if (s.Contains("o"))
{
s = s.Remove(s.IndexOf('o')) + "Foo" + s.Substring(s.IndexOf('o') + 1);
}
https://stackoverflow.com/questions/8809354
复制相似问题