C 计算每个角色的出现次数
我是C语言的新手,正在做家庭作业。我完成了大部分工作,但我不能通过教授使用的所有测试用例。他拒绝张贴自动分级机中使用的案例 我错过了哪些案例? 任何线索都将不胜感激C 计算每个角色的出现次数,c,counting,C,Counting,我是C语言的新手,正在做家庭作业。我完成了大部分工作,但我不能通过教授使用的所有测试用例。他拒绝张贴自动分级机中使用的案例 我错过了哪些案例? 任何线索都将不胜感激 Write a program to remove all the blank characters (space and tab) in a line. Then, count the number of appearances of each character. Input A single line with a max
Write a program to remove all the blank characters (space and tab) in a line.
Then, count the number of appearances of each character.
Input
A single line with a maximum length of 5000 characters
Output
First line: The line after removing all the blank characters.
If the line is empty, don’t print anything in the output.
Next lines: Each line contains a character that appears in the line and its count.
Note that, the characters must appear according to their ASCII number order. (http://www.asciitable.com)
#包括
int main(){
int c=0;
int字符[128]={0};//ASCII表的下标
int count=0;//读取的字符数
而(计数<5001&&(c=getchar())!=EOF){
//9->ASCII上的制表符,32->ASCII上的空格
如果(c!=9&&c!=32){
普查尔(c);
字符[c]++;
计数++;
}
}
fflush(stdout);
printf(“\n”);
对于(int i=0;i<128;i++){
如果(字符[i]!=0){
printf(“%c%d\n”,i,字符[i]);
}
}
返回0;
}
再次重申,任何帮助都将不胜感激
更新:
代码已更正。可能您不想编写
9
字符代表什么?!也许你的意思是如果(!isspace(c))
。请注意,输入与输出不交叉,因此您可以立即使用putchar()
,无需将文本累积到text
字符[index]=0
为什么?@dxiv应该是text[index]=0
显然:D字符[index]=0代码>这意味着,如果输入长度>256(假定最大值为5000),并且请不要使用,则您的程序将在数组边界之外写入。如果9
和32
分别表示换行符和空格的ASCII值,请使用正确的字符常量'\n'
和'
。
#include <stdio.h>
int main (){
int c = 0;
int characters[128] = {0}; // subscripts for the ASCII table
int count = 0; // number of characters been reading in
while(count < 5001 && (c = getchar()) != EOF) {
// 9 -> TAB on ASCII, 32 -> Space on ASCII
if (c != 9 && c != 32) {
putchar(c);
characters[c]++;
count++;
}
}
fflush(stdout);
printf("\n");
for (int i = 0; i < 128; i++) {
if (characters[i] != 0) {
printf("%c %d\n", i, characters[i]);
}
}
return 0;
}
characters[index] = 0;
text[index] = 0;