Behemot Behemot - 2 years ago 83
C# Question

char.IsWhiteSpace finds space at "wrong" position

I am working through the book on a sample code but got a bit confused and struggle to find (probably a simple) answer. I wrote the following code:

static void CharFunctionality()
{

Console.WriteLine("char.IsWhiteSpace('Hello There', 5): {0}", char.IsWhiteSpace("Hello There", 5));
Console.WriteLine("char.IsWhiteSpace('Hello There', 6): {0}", char.IsWhiteSpace("Hello There", 6));
Console.WriteLine();
Console.ReadKey();
}


when I run it I get the following output:

char.IsWhiteSpace('Hello There', 5): True
char.IsWhiteSpace('Hello There', 6): False


I would think that this should be the other way around? the 5th character is 'o' and the 6th is 'space'. I hope someone can point me in the right direction on my journey into the world of development :)

thank you!

Answer Source

The number you provide is the index of the letter in the string you want to look for. In you first case, it the letter in the 5th index of your strong. In C#, indexes (for arrays or for strings, doesn't matter) always start at index 0.

So in your string "Hello There", 'H' is in the index 0, 'e' is in the index 1, 'l' is in the index 2, etc. That means that the char in the 5th index is a white space.

This works this way in most programming languages. You must always start counting at 0.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download