在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;}
说明:
使用示例:
// 在ASP.NET页面或控制器中string test = "Hello 世界!𠀀"; // 包含扩展汉字int count = CountChineseCharacters(test); // 返回3
注意事项:
C语言统计一句话中字符串的个数
这两个我测试过,符合你的问题 一个是数组,一个是指针,选用指针好些。 #include int main() { int num = 0, word = 0, i = 0; char str[40]; gets(str); while(str[i] != \0) { if(str[i] == ) { word = 0; } else { if(0 == word) { num++; word = 1; } else { word = 1; } } i++; } printf(%d\n,num); return 0; } #include #include int main() { int num = 0, word = 0; char *str = null; str = (char *)malloc(sizeof(char)*40); gets(str); while(*str != \0) { if(*str == ) { word = 0; } else { if(0 == word) { num++; word = 1; } else { word = 1; } } str++; } printf(%d\n,num); return 0; }
编写一函数,由实参传递一个字符串,统计此字符串中字母、数字、空格和其他字符的个数,在主函数中输入字符串以及输出上述的结果(用C语言编写)
void count(char *s, int *a, int *b, int *c, int *d){ *a = *b = *c = *d = 0; while(*s) { if(A <= *s && *s <= Z || a <= *s && *s <= z) (*a)++; else if(0 <= *s && *s <= 9) (*b)++; else if(*s == ) (*c)++; else (*d)++; s++; }}
int main(){ char s[100]; int lc, dc, sc, oc; printf(输入字符串:\n); gets(s); count(s, &lc, &dc, &sc, &oc); printf(字母:%d\n, lc); printf(数字:%d\n, dc); printf(空格:%d\n, sc); printf(其它:%d\n, oc); return 0;}
C++输入一个字符串,得到这个字符串中字母的个数与数字的个数
#include














发表评论