简体   繁体   中英

C# Replacing part of string by start and end position

I have a string and I want to replace a part of it. The tricky part is that that I can't use Regex.replace, because I only know the start and end positions of the data in the string. For example, if the string looks like this:

I love cats, some more stuff here, we dont know how much more

And I have start=8 and end=11 . And I want to replace that part to whatever I need to. This time lets say dogs so the new string will look like:

I love dogs, some more stuff here, we dont know how much more

How I could do that?

Simplest way:

string replaced = original.Substring(0, start) + replacementText + 
                  original.Substring(end);

I had expected StringBuilder to have something which would do this, but I think you'd have to call Remove then Insert .

str.Substring(0, 8) + "replacement" + str.Substring(11);

它不是“优雅”,但它有效。

ReplaceAt(int index, int length, string replace)

Here's an extension method that doesn't use StringBuilder or Substring. This method also allows the replacement string to extend past the length of the source string.

//// str - the source string
//// index- the start location to replace at (0-based)
//// length - the number of characters to be removed before inserting
//// replace - the string that is replacing characters
public static string ReplaceAt(this string str, int index, int length, string replace)
{
    return str.Remove(index, Math.Min(length, str.Length - index))
            .Insert(index, replace);
}

When using this function, if you want the entire replacement string to replace as many characters as possible, then set length to the length of the replacement string:

"0123456789".ReplaceAt(7, 5, "Salut") = "0123456Salut"

Otherwise, you can specify the amount of characters that will be removed:

"0123456789".ReplaceAt(2, 2, "Salut") = "01Salut456789"

If you specify the length to be 0, then this function acts just like the insert function:

"0123456789".ReplaceAt(4, 0, "Salut") = "0123Salut456789"

I guess this is more efficient since the StringBuilder class need not be initialized and since it uses more basic operations. Hope this help

string newString = 
 String.Concat(
        originalString.Substring(0, start),
        replacementText, 
        originalString.Substring(end));

OR

StringBuilder sb = new StringBuilder(originalString);
sb
  .Remove(start, length)
  .Insert(start, replacementText);

Just for fun with LINQ:

const string S = "I love cats, some more stuff here, we dont know how much more";
const string Dogs = "dogs";

var res = S
    .Take(7)
    .Concat(Dogs)
    .Concat(S.Where((c, i) => i > 10));

var resultString = string.Concat(res);

Not elegant but funny solution :

string myString = "I love cats, some more stuff here, we dont know how much more";

        Regex expr = new Regex("cats");
        int start = 8;
        int end = 11;
        Match m =expr.Match(myString);
        if (m.Index == start-1 && m.Length == end - (start-1))
        {
            Console.WriteLine(expr.Replace(myString, "dogs")); 
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM