Check if String is All Lower or All Upper Case
Funny how sometimes there are so many ways to accomplish the same thing. In a project last week I needed to check if a user entered a sentence in all lower (or could have been upper) case. So I immediately went to the most simple solution; using the ToLower() method on the string object and comparing the original string input to the lower version of the same sentence. The code is shown below.
private bool IsAllLowerCase(string value)
{
return (value.Equals(value.ToLower()));
}
This is a simple method that should be fairly performant. I then started to think that I could also use a regular expression to do this as well. This is shown in the following code:
using System.Text.RegularExpressions;
private bool IsAllLowerCase(string value)
{
// Allow anything but upper case
return new Regex(@"^([^A-Z])+$").IsMatch(value);
}
I have seen many fancy, complicated versions of this, but for this situation I wanted to allow any character, number or punctuation, I just do not want upper case characters. This small little Regular Expression does the job quite nicely.
Here is the same code using the ToLower() method and regular expressions using Visual Basic.
Private Function IsAllLowerCase( _
ByVal value As String) As Boolean
Return (value.Equals(value.ToLower()))
End Function
Imports System.Text.RegularExpressions
Private Function IsAllLowerCase( _
ByVal value As String) As Boolean
Return New Regex("^([^A-Z])+$").IsMatch(value)
End Function
Of course, you can see that you can just flip this around to check to see if a string is all upper case too.
Good Luck With Your Coding,
Paul Sheriff
** SPECIAL OFFER FOR MY BLOG READERS **
Visit http://www.pdsa.com/Event/Blog for a free eBook on "Fundamentals of N-Tier".
Past Blog Content
Blog Archive
-
2015
-
2014 (18)
-
2013 (11)
-
2012 (19)
-
2011 (29)
-
2010 (19)
-
2009 (28)
-
2008 (0)
-
2007 (14)
-
2006 (6)