20

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

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

KyleMit
  • 30,350
  • 66
  • 462
  • 664
abc
  • 2,285
  • 5
  • 29
  • 64
  • I have to export a file, and import it to another application which throws errors if there are special signs like é,... – abc Apr 02 '12 at 11:35
  • 8
    Of course é or á are letters... – leppie Apr 02 '12 at 11:35
  • 1
    I don't know why they wouldn't be letters, but you could force them back to ascii, as in [this question](https://stackoverflow.com/a/2086575/) – Alexander Dec 07 '18 at 17:14

7 Answers7

31
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) ...
zmbq
  • 38,013
  • 14
  • 101
  • 171
12

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

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

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

H H
  • 263,252
  • 30
  • 330
  • 514
7

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

Sly
  • 15,046
  • 12
  • 60
  • 89
  • I think the second is better, the first might accept accented characters, too. – zmbq Apr 02 '12 at 11:38
  • not 100% sure, but as I remember it won't. I've had some trouble with that. \w won't match Norway's symbols for example. There is a way with enabling unicode: http://www.regular-expressions.info/unicode.html but I haven't tried it. – Sly Apr 02 '12 at 11:41
  • 2
    I'm not sure either. Since we're both sure [a-zA-Z] will work, and so will anybody reading the code, it's better. – zmbq Apr 02 '12 at 11:43
4

Update in .NET 7

There is now a Char.IsAsciiLetter function which would exactly meet the requirements

KyleMit
  • 30,350
  • 66
  • 462
  • 664
Brent
  • 4,611
  • 4
  • 38
  • 55
3

In C# 9.0 you can use pattern matching enhancements.

public static bool IsLetter(this char c) =>
    c is >= 'a' and <= 'z' or >= 'A' and <= 'Z';
Misha Zaslavsky
  • 8,414
  • 11
  • 70
  • 116
2
// 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);
Dor Cohen
  • 16,769
  • 23
  • 93
  • 161
-3

Use Linq for easy access:

if (yourString.All(char.IsLetter))
{
    //just letters are accepted.
}
ndnenkov
  • 35,425
  • 9
  • 72
  • 104
Zain AD
  • 3
  • 1