简体   繁体   中英

How to check first character of a string if a letter, any letter in C#

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

Try the following

string str = ...;
bool isLetter = !String.IsNullOrEmpty(str) && Char.IsLetter(str[0]);

尝试以下

bool isValid = char.IsLetter(name.FirstOrDefault());
return (myString[0] >= 'A' && myString[0] <= 'Z') || (myString[0] >= 'a' && myString[0] <= 'z')

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM