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);
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With