[ACCEPTED]-C# Replacing part of string by start and end position-replace

Accepted answer
Score: 23

Simplest way:

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

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

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

It's not "elegant", but it works.


Score: 2

ReplaceAt(int index, int length, string 16 replace)

Here's an extension method that 15 doesn't use StringBuilder or Substring. This 14 method also allows the replacement string 13 to extend past the length of the source 12 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 11 want the entire replacement string to replace 10 as many characters as possible, then set 9 length to the length of the replacement 8 string:

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

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

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

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

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

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

Score: 0
string newString = 
        originalString.Substring(0, start),


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


Score: 0

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
    .Concat(S.Where((c, i) => i > 10));

var resultString = string.Concat(res);


Score: 0

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


More Related questions