45

I want to take a string and check the first character for being a letter, upper or lower doesn't matter, but it shouldn't be special, a space, a line break, anything. How can I achieve this in C#?

Usama Abdulrehman
  • 1,041
  • 3
  • 11
  • 21
korben
  • 505
  • 1
  • 5
  • 6

4 Answers4

87

Try the following

string str = ...;
bool isLetter = !String.IsNullOrEmpty(str) && Char.IsLetter(str[0]);
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • 26
    Slightly shorter: `Char.IsLetter(str.FirstOrDefault())` – driis Aug 24 '10 at 19:45
  • 5
    @driis that works but it adds several unnecessary allocations to what should be an allocation free check – JaredPar Aug 24 '10 at 19:49
  • thank you everyone for your help, i wasn't sure who to award since you all helped, i just went with the highest number already figured first wins? thanks everyone though. – korben Aug 24 '10 at 19:57
10

Try the following

bool isValid = char.IsLetter(name.FirstOrDefault());
Patrick D'Souza
  • 3,491
  • 2
  • 22
  • 39
  • If the string is null you actually get a `System.ArgumentNullException: 'Value cannot be null.'` so FirstOrDefault is not useful here. – iCollect.it Ltd Oct 13 '20 at 11:04
0
return (myString[0] >= 'A' && myString[0] <= 'Z') || (myString[0] >= 'a' && myString[0] <= 'z')
Mark Mullin
  • 1,340
  • 1
  • 9
  • 21
0

You should look up the ASCII table, a table which systematically maps characters to integer values. All lower-case characters are sequential (97-122), as are all upper-case characters (65-90). Knowing this, you do not even have to cast to the int values, just check if the first char of the string is within one of those two ranges (inclusive).

user400348
  • 236
  • 2
  • 7
  • 2
    He didn't say that letters are restricted to the ASCII character set. – driis Aug 24 '10 at 19:47
  • @maxstar: Knowing that ASCII uses sequential values for `A-Z` and `a`-`z`, I would prefer Mark's solution over this, as his solution avoids using magic numbers. You could also adjust your solution to define constants somewhere to hold 97/122/65/90, but that is adding unneeded constants, so I still prefer Mark's solution. Of course, calling `Char.IsLetter` as suggested by JaredPar is even better. – Brian Aug 24 '10 at 20:34
  • I completely agree that using Char.IsLetter may be better. I am merely suggesting that korben look up the ASCII table to know that characters aren't just randomly floating in cyber space, but are systematically structured and mapped to numbers. I believe knowing this is more important and beneficial than simply getting an answer to the posted question, because this provides underlying understanding. And by the way, I meant exactly what Mark wrote: when I said "within one of those two ranges" I meant ranges of chars, not ints. Sorry for the misunderstanding. – user400348 Aug 24 '10 at 21:47