简体   繁体   English

如何检查字符串的第一个字符,如果是字母,C# 中的任何字母

[英]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#?我怎样才能在 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.您应该查找 ASCII 表,这是一个系统地将字符映射到整数值的表。 All lower-case characters are sequential (97-122), as are all upper-case characters (65-90).所有小写​​字符都是连续的 (97-122),所有大写字符 (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).知道这一点,您甚至不必强制转换为 int 值,只需检查字符串的第一个字符是否在这两个范围之一(包括)内。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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