计算字符串中不同字符的频率数 [英] Count the number of frequency for different characters in a string

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

问题描述

我目前尝试创建一个小程序,用户在文本区域中输入一个字符串,点击一个按钮,程序计算字符串中不同字符的频率,并在另一个文本区域显示结果。
例如步骤1: - 用户输入: - aaabbbbbbcccdd
步骤2: - 用户单击按钮
步骤3: - a 3
b 6
c 3
d 1​​
这是我到目前为止....

i am currently tried to create a small program were the user enter a string in a text area, clicks on a button and the program counts the frequency of different characters in the string and shows the result on another text area. E.g. Step 1:- User enter:- aaabbbbbbcccdd Step 2:- User click the button Step 3:- a 3 b 6 c 3 d 1 This is what I've done so far....

    public partial class Form1 : Form
    {
        Dictionary<string, int> dic = new Dictionary<string, int>();
        string s = "";
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            s = textBox1.Text;
            int count = 0;
            for (int i = 0; i < s.Length; i++ )
            {
                textBox2.Text = Convert.ToString(s[i]);
                if (dic.Equals(s[i]))
                {
                    count++;
                }
                else
                {
                    dic.Add(Convert.ToString(s[i]), count++);
                }
            }

        }
    }
}

任何想法或帮助如何计数,因为到现在程序是有一个运行时错误,当有相同的charachter时!

Any ideas or help how can I countinue because till now the program is giving a run time error when there are same charachter!!

谢谢您

推荐答案

您尝试将整个字典与字符串进行比较,但不会告诉您是否有键对应于字符串的字典。因为字典从不等于字符串,你的代码总是认为它应该添加一个新的项目,即使一个已经存在,这是运行时错误的原因。

You are attempting to compare the entire dictionary to a string, that doesn't tell you if there is a key in the dictionary that corresponds to the string. As the dictionary never is equal to the string, your code will always think that it should add a new item even if one already exists, and that is the cause of the runtime error.

使用 ContainsKey 方法检查字典中是否存在字符串

Use the ContainsKey method to check if the string exists as a key in the dictionary.

使用变量 count ,您将需要增加字典中的数字,并以一个计数初始化新项目:

Instead of using a variable count, you would want to increase the numbers in the dictionary, and initialise new items with a count of one:

string key = s[i].ToString();
textBox2.Text = key;
if (dic.ContainsKey(key)) {
  dic[key]++;
} else {
  dic.Add(key, 1);
}

这篇关于计算字符串中不同字符的频率数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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