Friday, June 19, 2009

Simple C# String character remover.

I search for a .Net method to remove a character, such as a space, from anywhere in a string. I found the String.Trim, String.Left, and String.Right, but I didn't see anything that removes a character from anywhere in the middle. Maybe my eyes are just not seeing it. Anyway I rolled my own as follows:


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. :-)

1 comment:

  1. Found an easier way: (Gotta luv Regex!)

    public string RemoveCharFromString(
    string str, char c)
    {
    return Regex.Replace(str, "[" + c.ToString() +
    "]", String.Empty);
    }

    ReplyDelete