![](/img/trans.png)
[英]C program: how to find the maximum/minimum frequency of a character in a string
[英]C program to find frequency of a character from a string
为什么代码不起作用?? 那个循环有什么问题吗?? 如果那么应该回答什么? 以及为什么不能。 请让我清楚。 :)
#include<stdio.h>
#include<string.h>
int main()
{
char s[1000];
int i,j=1,x,y; char k,l;
gets(s);
l = strlen(s);
scanf("%c",&k);
for(s[i]=0; s[i]<l; i++)
{
if(s[i]=='k')
j++;
}
printf("\n%c is %d time(s) in string",k,j);
return 0;
}
请检查这种方式。 您正在匹配字母“k”而不是变量。
if(s[i]==k)
首先使用l = strlen(s)+1;
而不是l = strlen(s);
. 然后将for循环中的s[i]=0
改为i = 0;
并使用i<l
而不是s[i]<l
。
另外,将if(s[i]=='k')
更改为if(s[i]==k)
。
完整示例:
#include<stdio.h>
#include<string.h>
int main()
{
char s[1000];
int i,j=0,l;
char k;
gets(s);
l = strlen(s)+1;
scanf("%c",&k);
for(i=0; i<l; i++)
{
if(s[i]== k)
j++;
}
printf("\n%c is %d time(s) in string",k,j);
return 0;
}
变量 l 的数据类型是 char。它应该被声明为 int 类型。 您已将 j 初始化为值 1 ,而本应使用 0 进行初始化。 for 循环不正确。 而不是 s[i] 使用 i 并检查条件 i < l 。 最后在 if 条件下用 k 替换 'k' 我希望这会帮助你得到想要的结果
我看你犯了很多错误,我把它们列出来:
代码示例:
#include <stdio.h> /* printf */
#include <stdlib.h> /* fgets */
#include <string.h> /* strlen */
#define MAX_LINE_LENGTH 1000
int main()
{
char k;
char line[MAX_LINE_LENGTH];
size_t count, length, i;
/* Reading a line/string */
printf("Please enter a line : ");
if (!fgets (line, MAX_LINE_LENGTH, stdin))
{
/* handle error */
printf("Failed to read input\n");
return 1;
}
/* calculating the length */
length = strlen(line) + 1;
/* Reading the letter to count its occurences */
printf("Please enter a letter : ");
scanf("%c",&k);
/*
* Counting the occurences of k in a string/line
*/
count = 0;
for(i = 0; i < length; ++i)
{
if(line[i] == k)
{
++count;
}
}
printf("%c is %d time(s) in string\n", k, count);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.