可能的重复: 如何替换。net中字符串的第一个实例?
假设我有一个字符串
string s = "Hello world.";
我怎么能取代第一个o在单词Hello让我们说Foo?
换句话说,我想以:
"HellFoo world."
我知道如何替换所有的o但我只想替换第一个o
可能的重复: 如何替换。net中字符串的第一个实例?
假设我有一个字符串
string s = "Hello world.";
我怎么能取代第一个o在单词Hello让我们说Foo?
换句话说,我想以:
"HellFoo world."
我知道如何替换所有的o但我只想替换第一个o
当前回答
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);
}
}
其他回答
有许多方法可以做到这一点,但最快的方法可能是使用IndexOf来查找想要替换的字母的索引位置,然后在想要替换的字母之前和之后用子字符串输出文本。
if (s.Contains("o"))
{
s = s.Remove(s.IndexOf('o')) + "Foo" + s.Substring(s.IndexOf('o') + 1);
}
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);
}
}
我认为你可以使用重载的Regex。Replace指定要替换的最大次数…
var regex = new Regex(Regex.Escape("o"));
var newText = regex.Replace("Hello World", "Foo", 1);