Jul 15, 2008

Check if a character is lower case (C#)

I am not quite sure if there is a "standard" way to check if a character is lower case but here is what I came up with:

private bool isLowerCase(char c)
{
  
return c > ((int)'a') - 1 && c < ((int)'z') + 1;
}

I think another approach would be to check if the character against the lowercase version of the character but this way you will have to first convert it to string (as the char type doesn't support .ToLower()), then to get the element at index 0 (so you again have a char variable. Here is the method to do so:

private bool isLowerCase(char c)
{
return c.ToString().ToLower()[0] == c;
}

the last approach is to check the character with regular expression:

private bool isLowerCase(
style="color:Blue;">char c)
{
return Regex.IsMatch(c.ToString(), "[a-z]");
}

Note that I haven't tested those approaches, I only worked with the first one, the other were written just to point you other approaches. If you want to use some of them you will need first to test them (although I think they will also work like charm). The other think to consider is the performance, when I have some free time I may perform some tests to see which approach is the fastest.

5 comments:

cypressx said...

I don't understand. Why not just :

bool isLowerCase(char c)
{
return (c>='a' && c<='z');
}

-- Yosif

Павелъ Дончевъ said...

Hi, Yosif, nice to hear from you again ;) !

To your question:
Because I didn't realized .NET will check the ordinal position of both characters if you use comparision operators.

However, I found the "standard" way - here.

P.S. Thanks a lot for your post!

P.P.S. I think in Delphi you can't directly compare two chars (not quite sure) so it may be side effect from Delphi background.

Anonymous said...

whats wrong with

Char.IsLower(char c)?

Павелъ Дончевъ said...

Very very old issue with it - the developer missed it ;). I then wrote another post to correct this error. See the next post please.

Павелъ Дончевъ said...

No problem, I like that kind of offtopic :).