How to check if a character is uppercase in C#
Overview
In C#, you can use the IsUpper() method see if a character is uppercase. This method indicates whether or not a certain character is uppercase.
Also, in a string, we can check if any of its characters is uppercase by specifying the index position of the character.
Syntax
// for a character
IsUpper(Char)
// for a string
IsUpper(String, Int32)
Parameters
Char: this is the character we want to check to see if it is uppercase.
String: this is a string that we want to check to see if any of its characters are uppercase.
Int32: this is the index position of the character in a string that we want to check to see if it is uppercase.
Return Value
The value returned is a Boolean. true is returned if the character is uppercase, else false is returned.
Coding example
In the coding example below, we create some characters and some strings and then check if some of the characters are uppercase using the IsUpper() method.
// use Systemusing System;// create classclass UppercaseChecker{// main methodstatic void Main(){// create characterschar c1 = 'H';char c2 = 'i';char c3 = 'E';// create stringsstring s1 = "Hi!";string s2 = "Edpresso";// check for uppercasebool a = Char.IsUpper(c1);bool b = Char.IsUpper(c2);bool c = Char.IsUpper(c3);bool d = Char.IsUpper(s1, 0); // first characterbool e = Char.IsUpper(s2, 1); // second character// print returned valuesConsole.WriteLine(a); // TrueConsole.WriteLine(b); // FalseConsole.WriteLine(c); // TrueConsole.WriteLine(d); // TrueConsole.WriteLine(e); // False}}
Explanation
-
In
line 10,line 11, andline 12we created characters,c1,c2, andc3. -
In
line 15andline 16, we created stringss1ands2. -
In line
19to21we checked if the characters created were uppercase using theIsUpper()method. -
In
line 22andline 23, we checked if some characters in the strings we created were uppercase using theIsUpper()method. We did this by passing the index positions of the characters. -
Finally, we printed the results from
line 26toline 30.
When the code runs, we see that all the characters specified were uppercase characters except character c2 and the second character of string s2, which returned false.