我正在用 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/