统计语句中重复字母的 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP