Possible Duplicate:
How do I replace the first instance of a string in .NET?可能的重复:如何替换。net中字符串的第一个实例?
Let's say I have the string:
假设我有弦
string s = "Hello world.";
how can I replace the first o
in the word Hello
for let's say Foo
?
如何替换单词Hello中的第一个o?
In other words I want to end up with:
换句话说,我想以:
"HellFoo world."
I know how to replace all the o's but I want to replace just the first one
我知道怎么替换所有的o但是我只想替换第一个
3 个解决方案
#1
170
I think you can use the overload of Regex.Replace to specify the maximum number of times to replace...
我认为您可以使用Regex的过载。替换指定要替换的最大次数…
var regex = new Regex(Regex.Escape("o"));
var newText = regex.Replace("Hello World", "Foo", 1);
#2
137
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);
}
here is an Extension Method that could also work as well per VoidKing
request
这里有一个扩展方法,它也可以根据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);
}
}
#3
11
There are a number of ways that you could do this, but the fastest might be to use IndexOf to find the index position of the letter you want to replace and then substring out the text before and after what you want to replace.
有很多方法可以做到这一点,但是最快的方法可能是使用IndexOf找到要替换的字母的索引位置,然后在要替换的字母前后对文本进行子字符串。
#1
170
I think you can use the overload of Regex.Replace to specify the maximum number of times to replace...
我认为您可以使用Regex的过载。替换指定要替换的最大次数…
var regex = new Regex(Regex.Escape("o"));
var newText = regex.Replace("Hello World", "Foo", 1);
#2
137
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);
}
here is an Extension Method that could also work as well per VoidKing
request
这里有一个扩展方法,它也可以根据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);
}
}
#3
11
There are a number of ways that you could do this, but the fastest might be to use IndexOf to find the index position of the letter you want to replace and then substring out the text before and after what you want to replace.
有很多方法可以做到这一点,但是最快的方法可能是使用IndexOf找到要替换的字母的索引位置,然后在要替换的字母前后对文本进行子字符串。