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

本文关键字:简单 解决方案 频率 字符 对象 字符串 | 更新日期: 2023-09-27 18:06:40

我要做的任务是显示字符串对象中每个字符的频率,目前我已经完成了部分代码,只是在我的脑海中没有完成这个任务的简单概念。到目前为止,我认为将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方法来获取所有唯一字母的计数。

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轻松地做到这一点,例如:

 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()
                                    });

下面是一个工作示例

更新:

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

下面是使用Dictionary<>

不使用Linq的Demo

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

其他人也发布了Linq方式,但我发现使用GetValueOrDefault的for循环稍微短一些。

string sign = "attitude";
foreach(var c in sign){
    counts[c] =  counts.GetValueOrDefault(c) + 1;
}

GetValueOrDefault(char key)返回0 (int的默认值)当字母的键在字典中还不存在时,并且一旦它存在就返回当前计数,因此我们只需在每次看到相同的字母时将其加1。