【问题标题】:issue counting number of letter occurrences in string [closed]问题计算字符串中字母出现的次数[关闭]
【发布时间】:2017-04-18 14:16:44
【问题描述】:

当我输入一个以字母“a”开头的字符串时,程序无法检查该字母并将其排除在外。如果我输入了一个字符串,但它不是第一个字符串,它会检查出来。

这是完整的问题:

编写一个程序,该程序将读取一行文本并输出文本中出现的所有字母的列表以及每个字母在该行中出现的次数。以用作标记值或分隔符的句点结束行。

字母应按以下顺序列出:出现频率最高的字母、下一个出现频率最高的字母,依此类推。

使用两个数组,一个保存字母,一个保存整数。您可以假设输入全部使用小写字母。例如,输入 do be go bo。应该产生类似于以下的输出:

字母出现次数 o 3 b 2 d 1 e 1

注意:可以修改书中选择排序算法的实现,对数组进行降序排序。您可以在程序中使用字符串类型或 c-string 类型。

代码:

 #include<iostream>
 #include<string>
 using namespace std;

 void sort(char letters[],int letter_count[])
  {
     for(int i=0; i<26; i++)
      {
        int max = i;
        for(int j=i; j<26; j++)
        {
           if(letter_count[j] > letter_count[max]) max = j;
        }
        int temp = letter_count[i];
        letter_count[i] = letter_count[max];
        letter_count[max] = temp;

         char local = letters[i];
         letters[i] = letters[max];
         letters[max] = letters[i];
         }
  }

 int main()
 { 
   string str;

   char letters[26];
   int letter_count[26] = {0 };
   cout <<"Enter a line of text :";
   getline(cin,str);
   for(int i=0; i<str.length(); i++)
   letter_count[str[i]-'a']++;
   for(int i=0; i<26; i++)
   letters[i] = static_cast<char> ('a'+i);

   sort(letters, letter_count);


   cout <<"Letter Numbers of Occurrence" << endl;
   for(int i=0; i<26; i++) {
          if(letter_count[i]!=0)
          cout << letters[i] << "        " << letter_count[i]<<endl;
          }
    return 0;
} 

【问题讨论】:

  • 调试器是解决此类问题的正确工具。 询问 Stack Overflow 之前,您应该逐行浏览您的代码。如需更多帮助,请阅读How to debug small programs (by Eric Lippert)。至少,您应该 [编辑] 您的问题,以包含一个重现您的问题的 Minimal, Complete, and Verifiable 示例,以及您在调试器中所做的观察。
  • 你能举一个导致你的问题的以'a'开头的字符串的例子吗?
  • @polb 导致我的问题的字符串例如是“apple”。
  • 这可能会帮助您寻找解决方案...我得到了 'bba' 的以下结果:Enter a line of text :bba Letter Numbers of Occurrence b 2 b 1 Press any key to continue . . .
  • @AlessandroScarlatti 没有注意到这一点。我现在正在测试输入“apple”。我测试了“do be do bo”,它工作正常。 Enter a line of text :do be do bo Letter Numbers of Occurrence o 3 b 2 d 2 e 1

标签: c++ arrays string sorting char


【解决方案1】:

在第 20 行发现问题,您尝试将 letters[i]letters[max] 交换。那条线应该是

letters[max] = local;

【讨论】:

  • 谢谢!它总是你忽略的小事.....
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-28
  • 1970-01-01
  • 2014-07-25
  • 2021-01-27
  • 2019-04-05
  • 2013-11-04
  • 2016-01-23
相关资源
最近更新 更多