We can use the Is.WhiteSpace
method in C# to check if a character is whitespace or not.
We can also check if any character in a string is whitespace by specifying the index position of the character in the string.
// for a character
IsWhiteSpace(Char)
// for a string
IsWhiteSpace(String, Int32)
Char
: This is the character we want to check for being a whitespace or not.
String
: This is the string we want to check to see if any of its characters are whitespace.
Int32
: This is the index position of the character in a string whose index position we want to check.
The value returned is a Boolean value. It returns true
if the character that was specified is whitespace. Otherwise, it returns false
.
In the code below, we will look at how a character is checked for being a whitespace or not. We will create some characters and strings and use the IsWhiteSpace()
method to check if any of them are whitespace, and then we will print their return values.
// use Systemusing System;// create classclass WhiteSpaceChecker{// main methodstatic void Main(){// create characterschar c1 = 'a';char c2 = ' ';// create some stringsstring s1 = "hello!";string s2 = " world!";// check for whitespace// charactersbool a = Char.IsWhiteSpace(c1);bool b = Char.IsWhiteSpace(c2);bool c = Char.IsWhiteSpace(s1, 3); // 4th characterbool d = Char.IsWhiteSpace(s2, 0); // first character// print returned valuesConsole.WriteLine(a); // FalseConsole.WriteLine(b); // TrueConsole.WriteLine(c); // FalseConsole.WriteLine(d); // True}}
As we can see above, ch2
and the character at the first position in string s2
are whitespaces. This is why they return True
on lines 26 and 28.