116

我想替换给定字符串中的第一次出现。

如何在 .NET 中完成此任务?

4

14 回答 14

145
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");
于 2008-09-26T18:17:06.503 回答
68

正如其马特所说, 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 实例来完成它。

于 2008-09-28T21:11:49.890 回答
16

看看Regex.Replace

于 2008-09-26T18:13:34.250 回答
16
using System.Text.RegularExpressions;

RegEx MyRegEx = new RegEx("F");
string result = MyRegex.Replace(InputString, "R", 1);

将首先找到F并将InputString其替换为R.

于 2010-06-10T07:21:19.370 回答
15

考虑到“唯一”,也许:

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");
于 2010-11-03T12:00:11.007 回答
9

在 C# 语法中:

int loc = original.IndexOf(oldValue);
if( loc < 0 ) {
    return original;
}
return original.Remove(loc, oldValue.Length).Insert(loc, newValue);
于 2008-09-26T18:20:09.993 回答
9

将执行此操作的 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);    
    } 
}
于 2008-09-26T18:22:19.177 回答
5

假设AA仅当它位于字符串的开头时才需要替换:

var newString;
if(myString.StartsWith("AA"))
{
  newString ="XQ" + myString.Substring(2);
}

如果您需要替换第一次出现的AA,无论字符串是否以它开头,请使用 Marc 的解决方案。

于 2010-11-03T12:00:35.303 回答
4

而且因为还需要考虑 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
于 2008-09-26T18:42:35.007 回答
3

的重载之一Regex.Replaceint“可以发生替换的最大次数”。显然,使用Regex.Replace纯文本替换可能看起来有点矫枉过正,但它肯定很简洁:

string output = (new Regex("AA")).Replace(input, "XQ", 1);
于 2010-11-03T12:12:04.783 回答
2

对于不介意参考的任何人Microsoft.VisualBasic,都有ReplaceMethod

string result = Microsoft.VisualBasic.Strings.Replace("111", "1", "0", 2, 1); // "101"
于 2017-03-01T13:36:52.360 回答
1

此示例抽象出子字符串(但速度较慢),但可能比 RegEx 快得多:

var parts = contents.ToString().Split(new string[] { "needle" }, 2, StringSplitOptions.None);
return parts[0] + "replacement" + parts[1];
于 2016-05-23T21:52:31.127 回答
0

更新的扩展方法利用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));
    }
于 2020-08-17T20:09:47.250 回答
-1
string abc = "AAAAX1";

            if(abc.IndexOf("AA") == 0)
            {
                abc.Remove(0, 2);
                abc = "XQ" + abc;
            }
于 2010-11-03T12:04:59.057 回答