從鍵盤輸入1行字串(每行最多輸入80個字符),
統計字串中所包含的各個英文小寫字符及其對應的數量。
**輸入格式要求:不要有任何提示資訊,直接輸入1行字符。
**輸出格式要求:按字母順序輸出統計結果,"%c=%d\n"
每行輸出一個字母的統計資訊。
如果某個字母沒有出現,則不輸出該字母的統計資訊。
如:輸入字串:
abc2ed a7bcdcd
則輸出:
a=2
b=2
c=3
d=3
e=1
參考答案:
#include <stdio.h>
#define BUFFER_SIZE 80
#define COUNT_SIZE 26
main( )
{
char str[BUFFER_SIZE+1]; //2
int count[COUNT_SIZE]={0}; //2
int i = 0;
gets(str); //2
for(i=0; str[i]!='\0'; i++) //1
{
if((str[i]>='a') && (str[i]<='z')) //2
count[str[i]-'a']++; //4
}
for(i=0; i<COUNT_SIZE; i++) //1
{
if(count[i]>0) //1
{
printf("%c=%d\n", i+'a', count[i]); //2
}
}
}
uj5u.com熱心網友回復:
#include <stdio.h>
#include <ctype.h>
#define BUFFER_SIZE 80
#define COUNT_SIZE 26
int main(void)
{
char str[BUFFER_SIZE+1]; //2
int count[COUNT_SIZE]={0}; //2
int i = 0;
//gets(str); //2
fgets(str, sizeof(str), stdin); //2
//for(i=0; str[i]!='\0'; i++) //1
for(i=0; str[i]; i++) //1
{
//if ((str[i]>='a') && (str[i]<='z')) //2
if (islower(str[i])) //2
count[str[i]-'a']++; //4
}
for(i=0; i<COUNT_SIZE; i++) //1
{
//if(count[i]>0) //1
if (count[i]) //1
//{
printf("%c=%d\n", i+'a', count[i]); //2
//}
}
}
供參考~
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/169714.html
標籤:C語言
