12

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?

Null
  • 1,950
  • 9
  • 30
  • 33
hs2d
  • 6,027
  • 24
  • 64
  • 103
  • 2
    `mid$(myString, 9, 12) = "dogs"` Oh, wait that's old VB/VBA. Intersting how succinct it was, though. – agent-j Jun 27 '11 at 18:49
  • possible duplicate of [how to replace part of string by position?](http://stackoverflow.com/questions/5015593/how-to-replace-part-of-string-by-position) – joce Apr 16 '13 at 21:30
  • Does this answer your question? [How to replace part of string by position?](https://stackoverflow.com/questions/5015593/how-to-replace-part-of-string-by-position) – malat Jun 08 '23 at 11:40

6 Answers6

23

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • How about a `Remove` and then `Insert` on the `string`? – Gabe Jun 27 '11 at 18:47
  • @Gabe: Yup, that would work - I think it would end up with fewer intermediate string values, but more copying. I think I'd also find this code simpler to understand :) – Jon Skeet Jun 27 '11 at 18:54
6
str.Substring(0, 8) + "replacement" + str.Substring(11);

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

Mike Caron
  • 14,351
  • 4
  • 49
  • 77
2

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

Valynk
  • 466
  • 7
  • 7
0
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);
Arthur P
  • 1,050
  • 9
  • 16
  • Why are you using a StringBuilder? – Gabe Jun 27 '11 at 18:59
  • StringBuilder will be a little faster. String.Concat is using it internally also. For 3 portions of concatenation, however, simple '+' can work a little faster - so it is just a good practice to use StringBuilder rather than string when you mutate strings. – Arthur P Jun 27 '11 at 19:19
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
    .Take(7)
    .Concat(Dogs)
    .Concat(S.Where((c, i) => i > 10));

var resultString = string.Concat(res);
Kirill Polishchuk
  • 54,804
  • 11
  • 122
  • 125
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")); 
        }
Alex
  • 1