字符串:这是一个字母数字为123的特殊字符@#!
这是我的程序:
static void Main()
{
Console.WriteLine("Enter a string to calculate alphabets,digits and special characters");
string userstr = Console.ReadLine();
int alphabet, splch, digits;
alphabet = splch = digits = 0;
for (int i = 0; i < userstr.Length; i++)
{
if (userstr[i] >= 'a' || userstr[i] <= 'z')
{
alphabet++;
}
else if (userstr[i] >= 0 || userstr[i] <= 9)
{
digits++;
}
else { splch++; }
}
Console.WriteLine("No of Alphabets {0},digits {1}, special characters {2} in given string are", alphabet, digits, splch);
}
答案 0 :(得分:2)
您有很多错误,
&&
而不是||
0
和9
使用char 代码(我很乐意将其转换为foreach
)
foreach (var c in userstr)
{
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')
alphabet++;
else if (c >= '0'&& c <= '9')
digits++;
else
splch++;
}
或
foreach (var c in input)
{
if (char.IsLetter(c))
alphabet++;
else if (char.IsDigit(c))
digits++;
else
splch++;
}