可能重复:
如何在.NET中替换字符串的第一个实例?
假设我有字符串:
string s = "Hello world.";
Run Code Online (Sandbox Code Playgroud)
我怎么能替换第一个o在这个词Hello的假设Foo?
换句话说,我想最终得到:
"HellFoo world."
Run Code Online (Sandbox Code Playgroud)
我知道如何更换所有o,但我想更换第一个
Red*_*dog 211
我想你可以使用Regex.Replace的重载来指定要替换的最大次数......
var regex = new Regex(Regex.Escape("o"));
var newText = regex.Replace("Hello World", "Foo", 1);
Run Code Online (Sandbox Code Playgroud)
Met*_*Man 171
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);
}
Run Code Online (Sandbox Code Playgroud)
这是一个扩展方法,也可以按照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);
}
}
Run Code Online (Sandbox Code Playgroud)
Mit*_*ers 11
您可以通过多种方式执行此操作,但最快的方法可能是使用IndexOf查找要替换的字母的索引位置,然后在要替换的内容之前和之后对文本进行子字符串输出.
| 归档时间: |
|
| 查看次数: |
131496 次 |
| 最近记录: |