views:

125

answers:

3

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

thanks in advance, hope this is easy for someone

+16  A: 

Try the following

string str = ...;
bool isLetter = !String.IsNullOrEmpty(str) && Char.IsLetter(str[0]);
JaredPar
Slightly shorter: `Char.IsLetter(str.FirstOrDefault())`
driis
@driis that works but it adds several unnecessary allocations to what should be an allocation free check
JaredPar
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
A: 
return (myString[0] >= 'A' && myString[0] <= 'Z') || (myString[0] >= 'a' && myString[0] <= 'z')
Mark Mullin
Letters are not restricted to A-Z. For example, Æ is a danish letter.
driis
The days of ASCII are gone. Now all the cool kids are using Unicode! http://www.joelonsoftware.com/articles/Unicode.html
Martinho Fernandes
mea culpa - esp since I do use unicode :-(
Mark Mullin
This will throw an exception if the string is empty. You need to check `!String.IsNullOrEmpty(myString)` first.
Brian
A: 

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

He didn't say that letters are restricted to the ASCII character set.
driis
@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
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.