This question already has an answer here:
-
Get Index of First non-Whitespace Character in C# String
11 answers
How would I count the amount of spaces at the start of a string in C#?
example:
" this is a string"
and the result would be 4. Not sure how to do this correctly.
Thanks.
Use Enumerable.TakeWhile
, Char.IsWhiteSpace
and Enumerable.Count
int count = str.TakeWhile(Char.IsWhiteSpace).Count();
Note that not only " "
is a white-space but:
White space characters are the following Unicode characters:
- Members of the SpaceSeparator category, which includes the characters SPACE (U+0020), OGHAM SPACE MARK (U+1680), MONGOLIAN VOWEL SEPARATOR (U+180E), EN QUAD (U+2000), EM QUAD (U+2001), EN SPACE (U+2002), EM SPACE (U+2003), THREE-PER-EM SPACE (U+2004), FOUR-PER-EM SPACE (U+2005), SIX-PER-EM SPACE (U+2006), FIGURE SPACE (U+2007), PUNCTUATION SPACE (U+2008), THIN SPACE (U+2009), HAIR SPACE (U+200A), NARROW NO-BREAK SPACE (U+202F), MEDIUM MATHEMATICAL SPACE (U+205F), and IDEOGRAPHIC SPACE (U+3000).
- Members of the LineSeparator category, which consists solely of the LINE SEPARATOR character (U+2028).
- Members of the ParagraphSeparator category, which consists solely of the PARAGRAPH SEPARATOR character (U+2029). The characters CHARACTER TABULATION (U+0009), LINE FEED (U+000A), LINE TABULATION (U+000B), FORM FEED (U+000C), CARRIAGE RETURN (U+000D), NEXT LINE (U+0085), and NO-BREAK SPACE (U+00A0).
You can use LINQ, because string
implements IEnumerable<char>
:
var numberOfSpaces = input.TakeWhile(c => c == ' ').Count();
input.TakeWhile(c => c == ' ').Count()
Or
input.Length - input.TrimStart(' ').Length
Try this:
static void Main(string[] args)
{
string s = " this is a string";
Console.WriteLine(count(s));
}
static int count(string s)
{
int total = 0;
for (int i = 0; i < s.Length; i++)
{
if (s[i] == ' ')
total++;
else
break;
}
return total;
}
While I like the Linq based answers here's a boring unsafe method that should be pretty fast
private static unsafe int HowManyLeadingSpaces(string input)
{
if (input == null)
return 0;
if (input.Length == 0)
return 0;
if (string.IsNullOrWhiteSpace(input))
return input.Length;
int count = 0;
fixed (char* unsafeChar = input)
{
for (int i = 0; i < input.Length; i++)
{
if (char.IsWhiteSpace((char)(*(unsafeChar + i))))
count++;
else
break;
}
}
return count;
}
int count = 0, index = 0, lastIndex = 0;
string s = " this is a string";
index = s.IndexOf(" ");
while (index > -1)
{
count++;
index = s.IndexOf(" ", index + 1);
if ((index - lastIndex) > 1)
break;
lastIndex = index;
}
Console.WriteLine(count);