字符串对象中字符频率的简单解决方案 [英] simple solution for characters frequency in string object

查看:56
本文介绍了字符串对象中字符频率的简单解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要完成的任务是显示字符串对象中每个字符的出现频率,目前我已经完成了部分代码,只是脑子里没有简单的概念完成这项任务。到目前为止,我一直认为将char更改为int类型可能有用。值得一提的是,我想避免使用此部分:if(letter ==‘a’)NumberCount ++;好像为那个简单的任务写那么多条件并没有效率,我正在考虑采用上述方法。我将不胜感激如何进一步编写代码.....我是c#

The task what I'm trying to do is about showing up the frequency of every single characters from the string object, for the moment I've done some part of code, just doesn't have the easy concept in my mind for finishing this task. So far I was thinking that it might be usefull to changing the char into int type. What is worth mentioning I'd like to avoid using the part: if (letter == 'a') NumberCount++; as if it wouldnt be efficient to write that much conditions for that simple task, and I'was thinking of doing it way mentioned above. I'd be gratefull for any sugestions of how to code it further.....I'm beginner at 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的方式来获取所有唯一字母的计数。

Here's a non Linq way to get the counts of all the unique letters.

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

然后找出有多少个 a

Then to find out how many "a"s there are

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

或获取所有计数

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

这篇关于字符串对象中字符频率的简单解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆