Hendra Anggrian Hendra Anggrian - 4 months ago 18
C# Question

How to check if a String contains any letter from a to z?


Possible Duplicate:

C# Regex: Checking for “a-z” and “A-Z”




I could just use the code below:

String hello = "Hello1";
Char[] convertedString = String.ToCharArray();
int errorCounter = 0;
for (int i = 0; i < CreateAccountPage_PasswordBox_Password.Password.Length; i++) {
if (convertedString[i].Equals('a') || convertedString[i].Equals('A') .....
|| convertedString[i].Equals('z') || convertedString[i].Equals('Z')) {
errorCounter++;
}
}
if(errorCounter > 0) {
//do something
}


but I suppose it takes too much line for just a simple purpose, I believe there is a way which is much more simple, the way which I have not yet mastered.

Answer

Replace your for loop by this :

errorCounter = Regex.Matches(yourstring,@"[a-zA-Z]").Count;

Remember to use Regex class, you have to using System.Text.RegularExpressions; in your import

Comments