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

C#WindowsStringChar

C# Problem Overview


> 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.

C# Solutions


Solution 1 - C#

What about:

//true if it doesn't contain letters
bool result = hello.Any(x => !char.IsLetter(x));

Solution 2 - C#

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

Solution 3 - C#

You could use RegEx:

Regex.IsMatch(hello, @"^[a-zA-Z]+$");

If you don't like that, you can use LINQ:

hello.All(Char.IsLetter);

Or, you can loop through the characters, and use isAlpha:

Char.IsLetter(character);

Solution 4 - C#

You can look for regular expression

Regex.IsMatch(str, @"^[a-zA-Z]+$");

Solution 5 - C#

For a minimal change:

for(int i=0; i<str.Length; i++ )
   if(str[i] >= 'a' && str[i] <= 'z' || str[i] >= 'A' && str[i] <= 'Z')
      errorCount++;

You could use regular expressions, at least if speed is not an issue and you do not really need the actual exact count.

Solution 6 - C#

Use regular expression no need to convert it to char array

if(Regex.IsMatch("yourString",".*?[a-zA-Z].*?"))
{
errorCounter++;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHendra AnggrianView Question on Stackoverflow
Solution 1 - C#OmarView Answer on Stackoverflow
Solution 2 - C#Ta Duy AnhView Answer on Stackoverflow
Solution 3 - C#KirbyView Answer on Stackoverflow
Solution 4 - C#Sanja MelnichukView Answer on Stackoverflow
Solution 5 - C#perhView Answer on Stackoverflow
Solution 6 - C#AnirudhaView Answer on Stackoverflow