2
string mystring = "bbbccc  ";

How to check if my string contains more than one consecutive whitespace?

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
user1765862
  • 13,635
  • 28
  • 115
  • 220

2 Answers2

14

I assume you're looking for multiple consecutive whitespaces.
I'd use System.Text.RegularExpressions.Regex for that.

Regex regex = new Regex(@"\s{2,}"); // matches at least 2 whitespaces
if (regex.IsMatch(inputString))
    // do something
Nolonar
  • 5,962
  • 3
  • 36
  • 55
  • You should be very careful when using '\s' to mean a 'white space character', because that includes more than just spaces in many regular expression implementations. When using this in .NET, it actually includes new line and tab characters as well (see [this](http://www.regular-expressions.info/shorthand.html) for further information). If this is important for you, you should use the answer from the linked/duplicate answer above instead of this answer. – Sheridan Feb 03 '16 at 14:57
6

This is probably a fast implementation:

public static bool HasConsecutiveSpaces(string text)
{
    bool inSpace = false;

    foreach (char ch in text)
    {
        if (ch == ' ')
        {
            if (inSpace)
            {
                return true;
            }

            inSpace = true;
        }
        else
        {
            inSpace = false;
        }
    }

    return false;
}

But if you don't really need to worry about speed, just use the regexp solution given in a previous answer.

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
  • Fastest solution in this thread as far as I can tell – Onkelborg Mar 11 '13 at 09:57
  • +1, yes this should do the job fine, there was no consecutive word in the original post and that messed up my answer :) – Habib Mar 11 '13 at 09:59
  • 1
    Yes, I think the OP clarified after you'd written your answer (which would have otherwise been correct!) – Matthew Watson Mar 11 '13 at 10:01
  • 1
    Good answer, but note that "whitespace" frequently refer to large collection of symbols (starting with `\n`, `\r`, `\t`and all sort of spaces) - if you need that than instead of checking for `== ' '` check Unicode class of the character with [`Char.IsWhiteSpace`](http://msdn.microsoft.com/en-us/library/1x308yk8.aspx) – Alexei Levenkov Sep 01 '15 at 15:11
  • 1
    Also NOTE: "return inSpace;" missing before last closing curly brace! – kasparspr Aug 01 '17 at 15:21
  • @hQuse Good point (it should be `false` that is returned if it finishes the loop) – Matthew Watson Aug 01 '17 at 15:38