如何從C#獲取字符串中漢字的個數?C#中使用正則表達式來從字符串中判斷出漢字,然后計數,從而得到字符串中的漢字個數。
先看這段代碼:
//定義一個函數,返回字符串中的漢字個數
public static int GetHanNumFromString(string str)
{
int count = 0;
Regex regex = new Regex(@"^[/u4E00-/u9FA5]{0,}$");
for (int i = 0; i < str.Length; i++)
{
if (regex.IsMatch(str[i].ToString()))
{
count++;
}
}
return count;
}
新聞熱點
疑難解答