One-Line C# #1 : Remove Whitespace from a string

Thought I'd post a quick extension method that I made today. Hope it helps someone.

 

public static string RemoveWhitespace(this string str)
{
    try
    {
        return new Regex(@"\s*").Replace(str, string.Empty);
    }
    catch (Exception)
    {
        return str;
    }
}

10 Comments

  • So it very rarely a good idea to suppress exceptions, this leads to problems in your code down the road that are hard to track down.

    You could also avoid Regex and make the code simpler by doing the following:

    public static string RemoveWhitespace(this string str)
    {
    return (str ?? string.Empty).Replace(" ", string.Empty);
    }

  • Not sure what you mean by express expectations. Plus your code doesn't remove the whitespace form the string, it just replaces "" with string.empty, the same value.

  • I'd be more explicit and do nothing if the string were null or empty.

    I think the regEx is to remove tabs and other whitespace, not just a space.

    if(String.IsNullOrEmpty(str))
    {
    return str;
    }
    else
    {
    return ...
    }

  • Ah should have checked for empty and null. Good point.

  • "catch (Exception)" is _always_ a bad idea. Only catch exceptions if you handle them. Otherwise don't!

  • ANy idea of a rugular expression to convert multiple spaces to single one.[also]
    like " k amr a n " into "k amr a n"

  • @Uwe But sometimes you just don't care and just want the application to keep moving with out something stupid (like removing whitespace) to slow you down.

  • @kamii47 Not sure, I'll do some research. Not a big regex builder guy.. trying to get into it though!

  • @kamii47:
    Try Regex.Replace(value, @"\s{2,}", " ")

  • If you *know* an exception can be raised then do what you can to prevent it in code *before* the exception is raised. Raising an exception is heavyweight C# in that it makes the CLR do a lot of work. You don't want to do this as part of a normal sequence of events. Then, let the application exception handler deal with the things that were really unexpected.

Comments have been disabled for this content.