Characters in C# can be any letter, number, or symbol, etc. The Char.IsLetter()
method helps us check if a character is categorized as a Unicode letter. In other words, it helps us confirm if a character is a letter and not a number or a symbol.
We can also call the Char.IsLetter()
method to check if a string contains a character that is a letter. To do this, we can pass the index position of the character that we want to check.
// for a character
IsLetter(Char)
// for a string
IsLetter(String, Int32)
Char
: the character we’re checking if it’s a letter or not.
String
: the string containing the character we’re checking if it’s a letter or not.
Int32
: the index position of the character in the string we’re checking if it’s a letter or not.
The value returned is a Boolean. It returns true
if the character in question is actually a letter. Otherwise, a false
is returned.
In the example below, we shall create some characters and some strings and check if they contain characters that are letters or not by using the Char.IsLetter()
method.
// use Systemusing System;// create classclass LetterChecker{// create main methodstatic void Main(){// create characterschar char1 = 's';char char2 = '4';char char3 = '#';// create stringsstring st1 = "hello";string st2 = "1234";// check for lettersbool a = Char.IsLetter(char1);bool b = Char.IsLetter(char2);bool c = Char.IsLetter(char3);bool d = Char.IsLetter(st1, 2); // 3rd positionbool e = Char.IsLetter(st2, 0); // first position// print returned valuesConsole.WriteLine(a);Console.WriteLine(b);Console.WriteLine(c);Console.WriteLine(d);Console.WriteLine(e);}}
From the code above, we discovered the characters that were actually letters by using the Char.IsLetter()
method.
Only line 20 and line 23 returned true
. This is because char1
which has the value 's'
is actually a letter. And string st1
has the value 'l'
in position 3, which is also a letter.
The rest returned false
because they are not letters.