1

I want to check how many successing spaces are in my string. It should be no more than one.

For example:

this is ok
this  is NOT ok
thisisok
this   is NOT ok
BTC
  • 2,975
  • 1
  • 19
  • 25
  • With *successing* you mean continuous? – Rahul Sep 01 '15 at 15:00
  • yes, i think i chose my words poorly. I mean consecutive repeating or continuous – BTC Sep 01 '15 at 15:02
  • 2
    Also see this http://stackoverflow.com/questions/15335371/check-does-string-contain-more-than-one-white-space – Habib Sep 01 '15 at 15:05
  • @AlexeiLevenkov The question you marked as a duplicate is not a duplicate of this question. This question is asking about successive strings while the duplicate is substrings appearing anywhere in the full string. The question Habib linked to is a more appropriate duplicate. – John Koerner Sep 01 '15 at 15:12
  • @JohnKoerner just reopen and dupelhammer as duplicate provided by Habbib - it is actually exact duplicate (the one I provided requires some thinking before applying as I've added in previous comment). And have more specific code then your good answer :) – Alexei Levenkov Sep 01 '15 at 15:14

2 Answers2

3

You can test to see if two consecutive spaces exist in the string, as that will also cover any string of spaces longer than 2. You can do this using the Contains method:

string testString = "this  is not OK";
if (testString.Contains("  "))
{
    // Bad
}
John Koerner
  • 37,428
  • 8
  • 84
  • 134
0

This should get you the logic for succession spaces in string literal

    static void Main(string[] args)
    {
        string str = "this  is NOT ok";
        int index = str.IndexOf(' ');
       //check if next character of space is also a space
        if (index >= 0 && str[index + 1] == ' ')
            Console.WriteLine("Not Ok String");
        else
            Console.WriteLine("OK String");
    }
Rahul
  • 76,197
  • 13
  • 71
  • 125