16

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 á?

Dor Cohen
  • 16,365
  • 23
  • 87
  • 156
abc
  • 2,125
  • 5
  • 28
  • 61
  • 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

6 Answers6

30
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
  • 36,789
  • 13
  • 91
  • 160
11

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

Henk Holterman
  • 250,905
  • 30
  • 306
  • 490
6

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

Sly
  • 14,608
  • 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
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,365
  • 23
  • 87
  • 156
1

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
  • 6,313
  • 10
  • 60
  • 108
-1

Use Linq for easy access:

if (yourString.All(char.IsLetter))
{
    //just letters are accepted.
}
ndnenkov
  • 34,386
  • 9
  • 72
  • 100
Zain AD
  • 7
  • 1