无法获得给定字符串中字母/数字/特殊字符的数量

时间:2019-01-02 04:07:30

标签: c#

字符串:这是一个字母数字为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);
    }

1 个答案:

答案 0 :(得分:2)

您有很多错误,

  1. 您需要&&而不是||
  2. 您需要考虑资金
  3. 您比较的数字有误,没有为09使用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++; 
}