我想替换给定字符串中的第一次出现。
如何在 .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提到的,还有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");
正如其马特所说, Regex.Replace是一个不错的选择,但是为了使他的答案更完整,我将用代码示例填充它:
using System.Text.RegularExpressions;
...
Regex regex = new Regex("foo");
string result = regex.Replace("foo1 foo2 foo3 foo4", "bar", 1);
// result = "bar1 foo2 foo3 foo4"
第三个参数,在这种情况下设置为 1,是要在输入字符串中从字符串开头替换的正则表达式模式的出现次数。
我希望这可以通过静态Regex.Replace重载来完成,但不幸的是,您似乎需要一个 Regex 实例来完成它。
using System.Text.RegularExpressions;
RegEx MyRegEx = new RegEx("F");
string result = MyRegex.Replace(InputString, "R", 1);
将首先找到F
并将InputString
其替换为R
.
考虑到“唯一”,也许:
int index = input.IndexOf("AA");
if (index >= 0) output = input.Substring(0, index) + "XQ" +
input.Substring(index + 2);
?
或更一般地说:
public static string ReplaceFirstInstance(this string source,
string find, string replace)
{
int index = source.IndexOf(find);
return index < 0 ? source : source.Substring(0, index) + replace +
source.Substring(index + find.Length);
}
然后:
string output = input.ReplaceFirstInstance("AA", "XQ");
在 C# 语法中:
int loc = original.IndexOf(oldValue);
if( loc < 0 ) {
return original;
}
return original.Remove(loc, oldValue.Length).Insert(loc, newValue);
将执行此操作的 C# 扩展方法:
public static class StringExt
{
public static string ReplaceFirstOccurrence(this string s, string oldValue, string newValue)
{
int i = s.IndexOf(oldValue);
return s.Remove(i, oldValue.Length).Insert(i, newValue);
}
}
假设AA
仅当它位于字符串的开头时才需要替换:
var newString;
if(myString.StartsWith("AA"))
{
newString ="XQ" + myString.Substring(2);
}
如果您需要替换第一次出现的AA
,无论字符串是否以它开头,请使用 Marc 的解决方案。
而且因为还需要考虑 VB.NET,所以我想提供:
Private Function ReplaceFirst(ByVal text As String, ByVal search As String, ByVal replace As String) As String
Dim pos As Integer = text.IndexOf(search)
If pos >= 0 Then
Return text.Substring(0, pos) + replace + text.Substring(pos + search.Length)
End If
Return text
End Function
的重载之一Regex.Replace
是int
“可以发生替换的最大次数”。显然,使用Regex.Replace
纯文本替换可能看起来有点矫枉过正,但它肯定很简洁:
string output = (new Regex("AA")).Replace(input, "XQ", 1);
对于不介意参考的任何人Microsoft.VisualBasic
,都有Replace
Method:
string result = Microsoft.VisualBasic.Strings.Replace("111", "1", "0", 2, 1); // "101"
此示例抽象出子字符串(但速度较慢),但可能比 RegEx 快得多:
var parts = contents.ToString().Split(new string[] { "needle" }, 2, StringSplitOptions.None);
return parts[0] + "replacement" + parts[1];
更新的扩展方法利用Span
以最小化新字符串的创建
public static string ReplaceFirstOccurrence(this string source, string search, string replace) {
int index = source.IndexOf(search);
if (index < 0) return source;
var sourceSpan = source.AsSpan();
return string.Concat(sourceSpan.Slice(0, index), replace, sourceSpan.Slice(index + search.Length));
}
string abc = "AAAAX1";
if(abc.IndexOf("AA") == 0)
{
abc.Remove(0, 2);
abc = "XQ" + abc;
}