Inline String Replace, there has to be a better way

  • Thread starter Thread starter Mike
  • Start date Start date
M

Mike

The code below does not seem very efficient if you have a very long string
and are doing many replace functions, there has to be a better way to do
this without reassigning the value type string over and over, any
suggestions? Thanks

string s = "ABCD";
s = s.Replace("AB", "12");
s = s.Replace("CD", "34");

// now s is "1234"
 
Regex has a Replace method with a MatchEvaluator callback you can use to select
which
replacement will occur. You'd do something like:

Regex.Replace("ABCD", "(AB|CD)", new MatchEvaluator(this.Match_AB_CD))

private string Match_AB_CD(Match m) {
switch(m.Groups[0].Value) {
case "AB": return "12"; break;
case "CD": return "34"; break;
}
}

I'm hoping the Regex engine is doing the *right* thing behind the scenes and I'm
pretty sure
it is based on some memory and performance profiling I've done for this method.
I used
these same Regex methods for things like the color coded tab controls in the
..NET QuickStarts.
(note I found a way to do a basic replacement rather than a MatchEvaluator
replacement then
though, which is a little faster than using the callback method as shown above).
 
Hi Mike,

Depending on how complex you would like to go, my suggestion is using Regular Expressions. These will replace pretty much anything in one hit providing you are familiar with them

Regards
Jonathan Rucker

----- Mike wrote: ----

The code below does not seem very efficient if you have a very long strin
and are doing many replace functions, there has to be a better way to d
this without reassigning the value type string over and over, an
suggestions? Thank

string s = "ABCD"
s = s.Replace("AB", "12")
s = s.Replace("CD", "34")

// now s is "1234
 
Thank for the quick replies...

StringBulder looks good, and I use it all the time, go figure. Now how
about a case insensitive inline replace?

Thanks Again!
 
Mike,

You can do this...

string s = "ABCD";
s = s.Replace("AB", "12").Replace("CD", "34");

....and keep on appending as many replace methods as you need.

Gary
 
That's essentially the same thing isn't it? Won't each .Replace() create a
new string?
 
Daniel

You are correct !! each .replace() will create a new string object.The following is a snippet from the MSDN :A String is called immutable because its value cannot be modified once it has been created. Methods that appear to modify a String actually return a new String containing the modification. If it is necessary to modify the actual contents of a string-like object, use the System.Text.StringBuilder class

Vinny
 
Back
Top