C# 判断中文字符的方法

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

方法一

在unicode字符串中,中文的范围是在4E00..9FFF:CJK Unified Ideographs。

通过对字符的unicode编码进行判断来确定字符是否为中文。

protected bool IsChineseLetter(string input,int index)

{ int code = 0;

intchfrom = Convert.ToInt32("4e00", 16); //范围(0x4e00~0x9fff)转换成int(chfrom~chend)

intchend = Convert.ToInt32("9fff", 16);

if (input != "")

{

code = Char.ConvertToUtf32(input, index); //获得字符串input中指定索引index处字符unicode编码

if (code >= chfrom&& code <= chend)

{

return true; //当code在中文范围内返回true

}

else

{

return false ; //当code不在中文范围内返回false

}

}

return false;

}

方法二:

public bool IsChina(string CString)

{

boolBoolValue = false;

for (inti = 0; i

{

if (Convert.ToInt32(Convert.ToChar(CString.Substring(i, 1))) < Convert.ToInt32(Convert.ToChar(128)))

{

BoolValue = false;

}

else

{

returnBoolValue = true;

}

}

returnBoolValue;

}

方法三:

///

/// 判断句子中是否含有中文

///

/// 字符串

public bool WordsIScn(string words)

{

stringTmmP;

for (inti = 0; i

{

TmmP = words.Substring(i, 1);

byte[] sarr = System.Text.Encoding.GetEncoding("gb2312").GetBytes(TmmP);

if (sarr.Length == 2)

{

return true;

}

}

return false;

}

方法四:

for (inti=0; i

{

Regex rx = new Regex("^[\u4e00-\u9fa5]$");

if (rx.IsMatch(s[i]))

// 是

else

// 否

}

正解!

\u4e00-\u9fa5 汉字的范围。

^[\u4e00-\u9fa5]$ 汉字的范围的正则

方法五

unicodeencodingunicodeencoding = new unicodeencoding();

byte [] unicodebytearray = unicodeencoding.getbytes( inputstring );

for(inti = 0; i

{

i++;

//如果是中文字符那么高位不为0

if ( unicodebytearray[i] != 0 )

{

}

方法六

///

/// 给定一个字符串,判断其是否只包含有汉字

///

///

///

public bool IsOnlyContainsChinese(string testStr)

{

char[] words = testStr.ToCharArray();

foreach (char word in words)

{

if ( IsGBCode(word.ToString()) || IsGBKCode(word.ToString()) ) // it is a GB2312 or GBK chinese word

{

continue;

}

else

{

return false;

}

}

return true;

}

//

/// 判断一个word是否为GB2312编码的汉字

///

///

///

private bool IsGBCode(string word)

{

byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(word);

if (bytes.Length<= 1) // if there is only one byte, it is ASCII code or other code {

return false;

}

else

{

byte byte1 = bytes[0];

byte byte2 = bytes[1];

if (byte1 >= 176 && byte1 <= 247 && byte2 >= 160 && byte2 <= 254) //判断是否是GB2312 {

return true;

}

else

{

return false;

}

}

}

相关文档
最新文档