Is there a better way of doing this...
MyString.Trim().Replace("&", "and").Replace(",", "").Replace(" ", " ")
.Replace(" ", "-").Replace("'", "").Replace("/", "").ToLower();
I've extended the string class to keep it down to one job but is there a quicker way?
public static class StringExtension
{
public static string clean(this string s)
{
return s.Replace("&", "and").Replace(",", "").Replace(" ", " ")
.Replace(" ", "-").Replace("'", "").Replace(".", "")
.Replace("eacute;", "é").ToLower();
}
}
Just for fun (and to stop the arguments in the comments) I've shoved a gist up benchmarking the various examples below.
The regex option scores terribly; the dictionary option comes up the fastest; the long winded version of the stringbuilder replace is slightly faster than the short hand.
this will be more efficient:
Maybe a little more readable?
Also add New In Town's suggestion about StringBuilder...
Quicker - no. More effective - yes, if you will use the
StringBuilder
class. With your implementation each operation generates a copy of a string which under circumstances may impair performance. Strings are immutable objects so each operation just returns a modified copy.If you expect this method to be actively called on multiple
Strings
of significant length, it might be better to "migrate" its implementation onto theStringBuilder
class. With it any modification is performed directly on that instance, so you spare unnecessary copy operations.There is one thing that may be optimized in the suggested solutions. Having many calls to
Replace()
makes the code to do multiple passes over the same string. With very long strings the solutions may be slow because of CPU cache capacity misses. May be one should consider replacing multiple strings in a single pass.I'm doing something similar, but in my case I'm doing serialization/De-serialization so I need to be able to go both directions. I find using a string[][] works nearly identically to the dictionary, including initialization, but you can go the other direction too, returning the substitutes to their original values, something that the dictionary really isn't set up to do.
Edit: You can use
Dictionary<Key,List<Values>>
in order to obtain same result as string[][]