如何检查字符串的第一个字符如果一个字母,任何一个字母

时间:2022-01-08 19:51:52

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

提前谢谢,希望这对某人来说很容易

4 个解决方案

#1


73  

Try the following

试试以下

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

#2


8  

Try the following

试试以下

bool isValid = char.IsLetter(name.FirstOrDefault());

#3


0  

return (myString[0] >= 'A' && myString[0] <= 'Z') || (myString[0] >= 'a' && myString[0] <= 'z')

#4


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

您应该查找ASCII表,该表系统地将字符映射到整数值。所有小写字符都是顺序字符(97-122),所有大写字符都是顺序字符(65-90)。了解这一点,您甚至不必强制转换到int值,只需检查字符串的第一个字符是否位于这两个范围(包括)中的一个。

#1


73  

Try the following

试试以下

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

#2


8  

Try the following

试试以下

bool isValid = char.IsLetter(name.FirstOrDefault());

#3


0  

return (myString[0] >= 'A' && myString[0] <= 'Z') || (myString[0] >= 'a' && myString[0] <= 'z')

#4


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

您应该查找ASCII表,该表系统地将字符映射到整数值。所有小写字符都是顺序字符(97-122),所有大写字符都是顺序字符(65-90)。了解这一点,您甚至不必强制转换到int值,只需检查字符串的第一个字符是否位于这两个范围(包括)中的一个。