写一个函数,由实参传来一个字符串,统计字符串中的字母,数字,空格和其他字符的个数,在主函数中输入字符串

如题所述

教你以后会经常用到的实用方法:正则表达式
public void caculate_num(string str)
{
Regex regex1 = new Regex("[a-zA-Z]");//匹配所有大小写字母
Regex regex2 = new Regex(@"\d");//匹配所有数字
Regex regex3 = new Regex(@"\s");//匹配所有空白符
int charNum = 0, intNum = 0, spaceNum = 0, otherNum = 0;
if (string.IsNullOrEmpty(str))
{
Console.WriteLine("字符串为空");
}
else
{
for (int i = 0; i < str.Length; i++)
{
if (regex1.IsMatch("" + str[i]))//isMatch参数必须为string类型
{
charNum++;
}
else if (regex2.IsMatch("" + str[i]))
{
intNum++;
}
else if (regex3.IsMatch("" + str[i]))
{
spaceNum++;
}
else
{
otherNum++;
}
}
Console.WriteLine("字母数:{0}", charNum);
Console.WriteLine("数字数:{0}", intNum);
Console.WriteLine("空格数:{0}", spaceNum);
Console.WriteLine("其他数:{0}", otherNum);
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-11-30
这个是利用char的数值对比实现的..是一个java程序..可以在里面实现你所要的那种效果,希望你看得懂,我是直接在主函数中写了..你可以自己分离代码出来..
public static void main(String[] args){
int ch=0,num=0,space=0;
String str = "this \tis my word -01239 !!";//测试的字符串;
char[] chArr = str.toCharArray();
for(int i=0;i<chArr.length;i++){
char c = chArr[i];
if(c<58 && c>=48){
num++;
}
else if((c>=65 && c<90) || (c>=97 && c<=122)){
ch++;
}
else if((c>=28 && c<=32) || (c==9 || c==10 || c==13)){
space++;
}
}
System.out.println("char = "+ch+"\nnum = "+num+"\nspace = "+space);
}本回答被网友采纳
第2个回答  2010-11-30
void a(char *pch,int &i,int& j,int &k);
相似回答