在ASP.NET中使用C#获取字符串中汉字个数的实现方法,可以通过以下两种常用方式实现(基于汉字的Unicode范围):

方法1:使用正则表达式(推荐)
using System.Text.RegularExpressions;
public int CountChineseCharacters(string input)
{
if (string.IsNullOrEmpty(input))
return 0;
// 匹配所有汉字(包括基本汉字和扩展区)
Regex regex = new Regex(@"p{IsCJKUnifiedIdeographs}");
return regex.Matches(input).Count;
}
方法2:遍历字符判断Unicode范围
public int CountChineseCharacters(string input)
{
if (string.IsNullOrEmpty(input))
return 0;
int count = 0;
foreach (char c in input)
{
// 判断是否在汉字Unicode范围内(基本汉字+扩展A区)
if (c >= 0x4E00 && c <= 0x9FA5)
{
count++;
}
}
return count;
}
说明:
-
正则表达式方法:
- 使用Unicode属性
p{IsCJKUnifiedIdeographs}匹配所有中日韩统一表意文字 - 优点:自动包含所有扩展汉字区(如扩展A/B/C/D等)
- 缺点:性能略低于直接遍历
- 使用Unicode属性
-
字符遍历方法:

0x4E00(19968) 到0x9FA5(40869) 是GB2312/GBK标准汉字范围- 如需支持扩展汉字(如𠀀等),可扩展范围:
if ((c >= 0x4E00 && c <= 0x9FA5) || (c >= 0x3400 && c <= 0x4DBF)) // 扩展A区
使用示例:
// 在ASP.NET页面或控制器中 string test = "Hello 世界!𠀀"; // 包含扩展汉字 int count = CountChineseCharacters(test); // 返回3
注意事项:
- 扩展汉字处理:
- 方法1自动支持所有Unicode汉字
- 方法2需手动添加扩展范围(如扩展A区
0x3400-0x4DBF)
- 性能考虑:
- 短字符串推荐使用正则表达式(代码简洁)
- 超长字符串建议用遍历方法(避免Regex开销)
- 编码确保:
- 源文件保存为UTF-8格式(避免字符解析错误)
- Web项目在
web.config中设置:<globalization requestEncoding="utf-8" responseEncoding="utf-8" />
建议优先使用正则表达式方案,能正确识别最新Unicode标准中的汉字字符(包括代理对字符)。
图片来源于AI模型,如侵权请联系管理员。作者:酷小编,如若转载,请注明出处:https://www.kufanyun.com/ask/290114.html

