编写一个 C 语言程序,通过示例查找字符串中所有字符的出现次数。
C 语言程序查找字符串中所有字符出现次数示例 1
此程序允许用户输入一个字符串(或字符数组)和一个字符值。然后,它将使用 If Else 语句 在该字符串中搜索并查找字符的所有出现次数。
#include <stdio.h>
#include <string.h>
int main()
{
char str[100], ch;
int i;
printf("\n Please Enter any String : ");
gets(str);
printf("\n Please Enter the Character that you want to Search for : ");
scanf("%c", &ch);
for(i = 0; i <= strlen(str); i++)
{
if(str[i] == ch)
{
printf("\n '%c' is Found at Position %d ", ch, i + 1);
}
}
return 0;
}

首先,我们使用 For 循环 遍历字符串中的每个字符。
for(i = 0; i <= strlen(str); i++)
{
if(str[i] == ch)
{
printf("\n '%c' is Found at Position %d ", ch, i + 1);
}
}
str[] = tutorial gateway
ch = t
For 循环第一次迭代: for(i = 0; i <= strlen(str); i++)
条件为 True,因为 0 <= 16。
在 C 编程 While 循环中,我们使用 If 语句 来检查 str[0] 是否等于用户指定的字符。
if(str[i] == ch) => if(t == t)
上述条件为 True。因此,编译器将执行 If 块内的 printf 语句。
这里,i 是索引位置(从零开始),i + 1 是实际位置。
第二次迭代: for(i = 1; 1 <= 16; 1++) – 条件为 True,因为 1 <= 16。
if(str[i] == ch) => if(t == l) – 条件为 False。因此,i 将递增。
第三次迭代: for(i = 2; 2 <= 16; 2++)
if(str[i] == ch) => if(t == t) – 条件为 True。因此,编译器将执行 If 块内的 printf 语句。
对剩余的迭代执行相同的操作。
C 语言程序查找字符串中所有字符出现次数示例 2
这个查找所有字符出现次数的程序与上面的相同。在这里,我们只是将 For 循环替换为 While 循环。
#include <stdio.h>
#include <string.h>
int main()
{
char str[100], ch;
int i;
i = 0;
printf("\n Please Enter any String : ");
gets(str);
printf("\n Please Enter the Character that you want to Search for : ");
scanf("%c", &ch);
while(str[i] != '\0')
{
if(str[i] == ch)
{
printf("\n '%c' is Found at Position %d ", ch, i + 1);
}
i++;
}
return 0;
}
Please Enter any String : Hello World
Please Enter the Character that you want to Search for : l
'l' is Found at Position 3
'l' is Found at Position 4
'l' is Found at Position 10
程序查找字符串中所有字符出现次数示例 3
这个程序与第一个示例相同,但这次我们使用了 函数 概念来分离逻辑。
#include <stdio.h>
#include <string.h>
void Find_AllOccurrence(char str[], char ch);
int main()
{
char str[100], ch;
printf("\n Please Enter any String : ");
gets(str);
printf("\n Please Enter the Character that you want to Search for : ");
scanf("%c", &ch);
Find_AllOccurrence(str, ch);
return 0;
}
void Find_AllOccurrence(char str[], char ch)
{
int i;
for(i = 0; str[i] != '\0'; i++)
{
if(str[i] == ch)
{
printf("\n '%c' is Found at Position %d ", ch, i + 1);
}
}
}
Please Enter any String : welcome to tutorial gateway
Please Enter the Character that you want to Search for : t
't' is Found at Position 9
't' is Found at Position 12
't' is Found at Position 14
't' is Found at Position 23