public string RemoveCharFromString(string str, char c)
{
if (String.IsNullOrEmpty(str)) return null;
StringBuilder sb = new StringBuilder();
foreach (char i in str)
{
if ( i != c) sb.Append( i );
}
return sb.ToString();
}
Simple enough. I bet there are better ways, but is it worth the time to search for
the perfect implementation? I guess it depends on the application requirements. You check for null or empty string before entering the loop and just return a null, and i suppose the whole thing could be encapsulated in a try-catch block for extra, extra precaution. No reason for that comes to mind, though. :-)
Found an easier way: (Gotta luv Regex!)
ReplyDeletepublic string RemoveCharFromString(
string str, char c)
{
return Regex.Replace(str, "[" + c.ToString() +
"]", String.Empty);
}