C# 检查字符是否为字母

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9975640/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 11:27:22  来源:igfitidea点击:

check if char isletter

c#.netchar

提问by Karl

i want to check if a string only contains correct letters. I used Char.IsLetterfor this. My problem is, when there are chars like é or á they are also said to be correct letters, which shouldn't be.

我想检查一个字符串是否只包含正确的字母。我用过Char.IsLetter这个。我的问题是,当有像 é 或 á 这样的字符时,它们也被认为是正确的字母,这不应该是。

is there a possibility to check a char as a correct letter A-Z or a-z without special-letters like á?

是否有可能将字符检查为正确的字母 AZ 或 az 而没有像 á 这样的特殊字母?

采纳答案by zmbq

bool IsEnglishLetter(char c)
{
    return (c>='A' && c<='Z') || (c>='a' && c<='z');
}

You can make this an extension method:

您可以将其设为扩展方法:

static bool IsEnglishLetter(this char c) ...

回答by Sly

You can use regular expression \wor [a-zA-Z]for it

您可以使用正则表达式\w[a-zA-Z]为它

回答by Dor Cohen

// Create the regular expression
string pattern = @"^[a-zA-Z]+$";
Regex regex = new Regex(pattern);

// Compare a string against the regular expression
return regex.IsMatch(stringToTest);

回答by Henk Holterman

You can use Char.IsLetter(c) && c < 128. Or just c < 128by itself, that seems to match your problem the closest.

您可以使用 Char.IsLetter(c) && c < 128. 或者就c < 128其本身而言,这似乎与您的问题最接近。

But you are solving an Encodingissue by filtering chars. Do investigate what that other application understands exactly.

但是您正在通过过滤字符来解决编码问题。一定要调查其他应用程序完全理解的内容。

It could be that you should just be writing with Encoding.GetEncoding(someCodePage).

可能是您应该使用Encoding.GetEncoding(someCodePage).

回答by Zain AD

Use Linqfor easy access:

使用Linq轻松访问:

if (yourString.All(char.IsLetter))
{
    //just letters are accepted.
}