Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using String.Replace() with an index instead of a string for the argument?

Tags:

c#

This seems like a simple problem but I'm not sure how to tackle it. I have a line of code that removes a part of a string. I simply want to change this from just removing to replacing it with something else. Is there a way I can use the string.replace with the index like I do in the following code sample?

output = output.Remove(m.Index, m.Length);
like image 428
proseidon Avatar asked Aug 12 '13 15:08

proseidon


2 Answers

No, there's nothing to do this. The simplest approach would be to just use Substring and string concatenation:

public static string Replace(string text, int start, int count,
                             string replacement)
{
    return text.Substring(0, start) + replacement 
         + text.Substring(start + count);
}

Note that this ensures you definitely won't replace other sections of the string which also happen to match that text.

like image 144
Jon Skeet Avatar answered Sep 19 '22 00:09

Jon Skeet


All great answers, you can also do this:

  String result = someString.Remove(m.Index, m.Length).Insert(m.Index, "New String Value");

It's not the prettiest code but it works.

It will generally be better to write this into a extension method or some sort of base functionality so you don't have to repeat yourself.

like image 33
jacqijvv Avatar answered Sep 21 '22 00:09

jacqijvv