How to check if a character is a whitespace in C#

Overview

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.

Syntax

// for a character
IsWhiteSpace(Char)
// for a string
IsWhiteSpace(String, Int32)

Parameters

  • 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.

Return value

The value returned is a Boolean value. It returns true if the character that was specified is whitespace. Otherwise, it returns false.

Code example

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 System
using System;
// create class
class WhiteSpaceChecker
{
// main method
static void Main()
{
// create characters
char c1 = 'a';
char c2 = ' ';
// create some strings
string s1 = "hello!";
string s2 = " world!";
// check for whitespace
// characters
bool a = Char.IsWhiteSpace(c1);
bool b = Char.IsWhiteSpace(c2);
bool c = Char.IsWhiteSpace(s1, 3); // 4th character
bool d = Char.IsWhiteSpace(s2, 0); // first character
// print returned values
Console.WriteLine(a); // False
Console.WriteLine(b); // True
Console.WriteLine(c); // False
Console.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.

Free Resources