c# - Visual C# Windows 窗体应用程序中的字符频率

标签 c# winforms

我正在用 Visual C# Windows 窗体应用程序开发一个程序。 我需要找出文本框中的字符数并在列表框中显示每个字符的出现频率。我有以下代码:

private void btnCheckFrequency_Click(object sender, EventArgs e)
{
    lstFreqMeter.Items.Clear();

    string str;
    int c = 1;
    int strlen;

    str = txtString.Text;

    strlen = txtString.TextLength;

    int[] counter = new int[strlen];

    for (int i = 0; i < strlen; i++)
    {
        for (int j = i + 1; j < strlen; j++)
        {
            if (str[i] == str[j])
            {
                c += 1;

            }
        }
        counter[i] = c;
        c = 1;
    }
    for (int k = 0; k < counter.Length; k++)
    {
        lstFreqMeter.Items.Add(counter[k]);
    }
}

在这段代码中,当我单击“检查频率”按钮时,程序会输出每个字符和重复字符以及我们不需要的空格的频率作为输出。

最佳答案

3 个循环来完成这是你出错的地方。我认为你试图让它变得太复杂。

给出家庭作业问题的答案是不受欢迎的,但一些关于方向的提示应该会有所帮助。

  • 声明 Dictionary<char, int>
  • 只做一个循环。对于字符串中的每个字符。
  • 在循环内,填充 Dictionary<char, int>与你的结果。
  • 如果字典中存在该char,则将int设为int++,如果不存在,则将该char添加到字典中,int为1。
  • 在循环外,将范围添加到您的 lstFreqMeter.Items。

关于c# - Visual C# Windows 窗体应用程序中的字符频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19499694/

相关文章:

c# - 使用 html agility xpath 查找 webdriver 元素

c# - 如何防止窗口标题栏上出现“无响应”消息?

c# - 如何通过win forms c#将数据发布到网站

c# - 如何从 DataGridViewComboBoxColumn 获取选定值?

c# - 检查 TreeView 是否有变化?

c# - Umbraco 自定义部分中的多级树

c# - 为什么将 int.MinValue 除以 -1 在未经检查的上下文中抛出 OverflowException?

c# - "Invalid column name"使用 EntityFramework.Extended 执行更新时出错

c# - EF5 和 Winform 的 MySql 异常

c# - 编译器是否优化了字符串文字?