判断一个字符串是不是全部为汉字。关于汉字的,在网上找到最多的就是正则表达式来处理,但是在我机器上从来没有成功过。于是找了很多种方法来解决。最理想的是方法一。
方法一:
public bool ValidateChinese(string s)
{
int max = s.Length;
for (int i = 0; i < max; i++)
{
if (char.GetUnicodeCategory(s, i) != System.Globalization.UnicodeCategory.OtherLetter)
{
return false;
}
}
return true;
}
方法二:采用ASCII码的方式,不能完全判断是汉字,例如输入全角的标点符号就能通过
public bool ValidateChinese(string s)
{
int max = s.Length;
for (int i = 0; i < max; i++)
{
if ((int)s[i] <= 127)
{
return false;
}
}
return true;
}
方法三:采用UNICOD的汉字编码。我的机器上没有通过
public bool ValidateChinese(string s)
{
char [] c = s.ToCharArray();
int max = c.Length;
for (int i = 0; i < max; i++)
{
if (c[i] >= 0x4e00 && c[i] <= 0x9fbb)
{
return false;
}
}
return true;
}
方法四:正则表达式验证。我的机器上没有通过
public bool ValidateChinese(string s)
{
int max = s.Length;
for (int i = 0; i < max; i++)
{
if (Regex.IsMatch(s[i].ToString(), @"[\u4e00-\u9fbb]+$"))
{
return false;
}
}
return true;
}