統計語句中重複字母的 C 程式。


問題

編寫一個程式來計算使用者在控制檯輸入的字母。使用 strlen() 函式,列印字母在句子中重複出現的次數。

解決方案

我們使用的計數字母的邏輯如下 −

  • 要求使用者在執行時輸入一個句子
printf("Enter a sentence
"); gets(str);
  • 要求使用者在執行時輸入一個字母
printf("Enter a character to check how many times it is repeating
"); scanf("%c",&c);
  • 計算句子中字母的邏輯如下 −
for(i=0;i<strlen(str);i++){
   if(str[i]==c){
      count++;
   }
}
  • 最後列印計數

示例

以下是計算句子中重複次數的字母的 C 程式 −

 即時演示

#include<stdio.h>
#include<string.h>
main(){
   int i,count=0;
   char c,str[100];
   printf("Enter a sentence
");    gets(str);    printf("Enter a character to check how many times it is repeating
");    scanf("%c",&c);    for(i=0;i<strlen(str);i++){       if(str[i]==c){          count++;       }    }    printf("Letter %c repeated %d times
",c,count); }

輸出

執行上述程式時,它會產生以下輸出 −

Enter a sentence
Here are the C Programming question and answers
Enter a character to check how many times it is repeating
n
Letter n repeated 4 times

更新於: 2021-03-25

6K+ 檢視次數

開啟您的 職業生涯

完成課程以獲得認證

開始學習
廣告
© . All rights reserved.