統計字符個數
題目:假設輸入一行字串,
統計其中小寫字母出現的次數,并按照出現次數的多少依次輸出,
當出現相同次數的字母時,按照字母的先后順序依次輸出
例如:“I love programming@C with class and java”
輸出:

分析:題目要求統計小寫字母,則可使用 islower() 函式,
(PS:需要參考頭檔案<ctype.h>),將小寫字母錄入,
對于出現相同次數的字母,還要按照字符的ANSCII進行排序,
我們想到可以用陣列來順序存盤a~z的出現次數,
定義陣列 int arr[26];
#include<stdio.h>
#include<string.h>
#include<assert.h>
#include<ctype.h>
void calc_charnum(char* p)
{
int count[26] = { 0 };
int i, j;
int max=0; //max為字母出現的最大次數
assert(p);
for (i = 0; *p != '\0'; i++)
{
if (islower(*p)) //小寫字母則錄入
{
max = ++count[(int)*p - 97] > max ? count[(int)*p - 97] : max;
//以陣列的形式存盤字符
//p++; //放在里面發生錯誤,到'.'時變為死回圈
}
p++;
}
for (i = 1; i <= max; i++)
{
int flag = 0;
for (j = 0; j < 26; j++)
{
if (i == count[j]) //根據出現次數找出對應的字母
{
printf("%c", j+97);//列印字符
flag = 1;
}
}
if (flag)
printf(" :%d\n", i); //在字母后面輸出相應的次數
}
}
int main()
{
char arr[] = "I love programming@C with class and java";
calc_charnum(arr);
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/266015.html
標籤:其他
上一篇:optisystem中器件的學習(4-Test Sets/Passives Library/Optical Switches)
下一篇:C語言 | 學習使用異或^
