C# 如何检查字符串是否包含从 a 到 z 的任何字母?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12884610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if a String contains any letter from a to z?
提问by Hendra Anggrian
Possible Duplicate:
C# Regex: Checking for “a-z” and “A-Z”
可能的重复:
C# 正则表达式:检查“az”和“AZ”
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.
但我想只是为了一个简单的目的需要太多的线,我相信有一种更简单的方法,我还没有掌握的方法。
采纳答案by Ta Duy Anh
Replace your for loopby this :
用for loop这个替换你的:
errorCounter = Regex.Matches(yourstring,@"[a-zA-Z]").Count;
Remember to use Regexclass, you have to using System.Text.RegularExpressions;in your import
记得使用Regex类,你必须using System.Text.RegularExpressions;在你的导入
回答by Sanja Melnichuk
回答by Kirby
You could use RegEx:
您可以使用正则表达式:
Regex.IsMatch(hello, @"^[a-zA-Z]+$");
If you don't like that, you can use LINQ:
如果你不喜欢那样,你可以使用 LINQ:
hello.All(Char.IsLetter);
Or, you can loop through the characters, and use isAlpha:
或者,您可以遍历字符,并使用 isAlpha:
Char.IsLetter(character);
回答by Anirudha
Use regular expression no need to convert it to char array
使用正则表达式无需将其转换为字符数组
if(Regex.IsMatch("yourString",".*?[a-zA-Z].*?"))
{
errorCounter++;
}
回答by perh
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.
您可以使用正则表达式,至少在速度不是问题并且您并不真正需要实际精确计数的情况下。
回答by Omar
What about:
关于什么:
//true if it doesn't contain letters
bool result = hello.Any(x => !char.IsLetter(x));

