簡體   English   中英

無法獲得給定字符串中字母/數字/特殊字符的數量

[英]Unable to get the number of alphabets/digits/special characters in a given string

字符串:這是一個字母數字為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. 您需要&&而不是||
  2. 你需要考慮資本
  3. 您比較數字錯誤而未將char用作09

代碼(我擁有將其轉換為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++; 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM