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:
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With