【发布时间】: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