字符串对象中字符频率的简单解决方案

simple solution for characters frequency in string object

我想做的任务是显示字符串对象中每个字符的频率,目前我已经完成了部分代码,只是没有简单的概念我完成这项任务的想法。到目前为止,我认为将 char 更改为 int 类型可能会有用。值得一提的是我想避免使用以下部分:if (letter == 'a') NumberCount++;好像为那个简单的任务写那么多条件是没有效率的,我正在考虑按照上面提到的方式来做。对于如何进一步编码的任何建议,我将不胜感激.....我是 c#

的初学者
 class Program
 {
    static void Main(string[] args)
    {
       string sign = "attitude";
       for (int i = 0; i < sign.Length; i++)
       {
          int number = sign[i]; // changing char into int

       } 

您可以像这样使用 Linq 轻松做到这一点:

 string sign = "attitude";
 int count = sign.Count(x=> x== 'a');

或者如果您希望所有字符都计数,则:

 string sign = "attitude";
 var alphabetsCount = sign.GroupBy(x=> x)
                          .Select(x=>new 
                                    {
                                      Character = x.Key, 
                                      Count = x.Count()
                                    });

Here is a working Example

更新:

如果没有 Linq,您可以使用循环来完成并在字典中跟踪它,例如:

string sign = "attitude";
Dictionary<char,int> dic = new Dictionary<char,int>();
foreach(var alphabet in sign)
{
    if(dic.ContainsKey(alphabet))
        dic[alphabet] = dic[alphabet] +1;
    else
        dic.Add(alphabet,1);
}

Here is Demo without Linq using Dictionary<>

这是一种非 Linq 方法来获取所有唯一字母的计数。

var characterCount= new Dictionary<char,int>();
foreach(var c in sign)
{
    if(characterCount.ContainsKey(c))
        characterCount[c]++;
    else
        characterCount[c] = 1;
}

然后求出有多少个"a"

int aCount = 0;
characterCount.TryGetValue('a', out aCount);

或获取所有计数

foreach(var pair in characterCount)
{
    Console.WriteLine("{0} - {1}", pair.Key, pair.Value);
}

如果您想在没有 Linq 的情况下实现它,请尝试

var charDictionary = new Dictionary<char, int>();
string sign = "attitude";
foreach(char currentChar in sign)
{
    if(charDictionary.ContainsKey(currentChar))
    { charDictionary[currentChar]++; }
    else
    { charDictionary.Add(currentChar, 1); }
}
class Program
    {
        static void Main(string[] args)
        {

            char ch;
            Console.Write("Enter a string:");
            string str = Console.ReadLine();
            for (ch = 'A'; ch <= 'Z'; ch++)
            {
                int count = 0;
                for (int i = 0; i < str.Length; i++)
                {
                    if (ch==str[i] || str[i] == (ch + 32))
                    {
                        count++;
                    }
                }
                if (count > 0)
                {
                    Console.WriteLine("Char {0} having Freq of {1}", ch, count);
                }
            }
            Console.Read();
        }
    }