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

问题描述 投票:1回答:4

我正在尝试做的任务是关于显示字符串对象中每个字符的频率,目前我已经完成了部分代码,只是在我的脑海中没有简单的概念来完成这个任务。到目前为止,我一直认为将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

       } 
c# character frequency
4个回答
6
投票

这是一种非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);
}

6
投票

您可以使用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<>


1
投票

如果你想在没有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); }
}

0
投票
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();
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.