教你以后会经常用到的实用方法:正则表达式
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);
}
}
温馨提示:答案为网友推荐,仅供参考