How do I replace the *first instance* of a string

2019-01-01 06:55发布

I want to replace the first occurrence in a given string.

How can I accomplish this in .NET?

14条回答
十年一品温如言
2楼-- · 2019-01-01 07:27

Taking the "first only" into account, perhaps:

int index = input.IndexOf("AA");
if (index >= 0) output = input.Substring(0, index) + "XQ" +
     input.Substring(index + 2);

?

Or more generally:

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);
}

Then:

string output = input.ReplaceFirstInstance("AA", "XQ");
查看更多
刘海飞了
3楼-- · 2019-01-01 07:29

In C# syntax:

int loc = original.IndexOf(oldValue);
if( loc < 0 ) {
    return original;
}
return original.Remove(loc, oldValue.Length).Insert(loc, newValue);
查看更多
十年一品温如言
4楼-- · 2019-01-01 07:33

Regex.Replace, especially RegEx.Replace(string, string, int), is probably what you're looking for. That or String.IndexOf which will give you the index and then you can cut and rebuild the string with the new text you want.

An example demonstrating the latter (as first demonstrated by @David Humpohl):

string str = "Hello WorldWorld";

str = ReplaceFirst(str, "World", "StackOverflow ");

...

string ReplaceFirst(string text, string search, string replace)
{
    int pos = text.IndexOf(search);
    if (pos >= 0)
    {
        return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
    }
    return text;
}
查看更多
泛滥B
5楼-- · 2019-01-01 07:36
using System.Text.RegularExpressions;

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

will find first F in InputString and replace it with R.

查看更多
春风洒进眼中
6楼-- · 2019-01-01 07:37

For anyone that doesn't mind a reference to Microsoft.VisualBasic, there is the Replace Method:

string result = Microsoft.VisualBasic.Strings.Replace("111", "1", "0", 2, 1); // "101"
查看更多
浪荡孟婆
7楼-- · 2019-01-01 07:40

Take a look at Regex.Replace.

查看更多
登录 后发表回答