我正在尝试计算一个字符在字符串中出现的次数。我想用 for 循环对每个字符进行计数,该循环还有另一个循环遍历字符串的每个字符。我不确定它有什么问题,或者是否可以这样做。我已经看到了其他可以完成的方法,但我想知道我是否接近实现它或者我的代码完全错误。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char A[100], ch;
int cnt[100]={};
gets(A);
int x = strlen(A)-1;
int i=0;
for(ch='a';ch<='z';ch++)
{
for(i = 0; i <= x; i++)
{
if(A[i]==ch)
cnt[i]++;
}
printf("%c is %d times in string\n", ch, cnt[i]);
}
return 0;
}
给你!和你的问题类似,有问题可以追问。
#include <stdio.h>
int count(char *p, char t) // Function to count occurence //
{
int i=0;
while(p[0]!= '\0')
{
if(p[0]==t)
{
i++;
}
p++;
}
return i;
}
int main()
{
char s[1000],c;
printf("Enter the string: ");
scanf("%s",s);
printf("Enter the character: ");
scanf(" %c",&c);
int j = count(s,c); // Function call //
printf("The occurence of %c in string is %d",c,j);
return 0;
}