[英]C program to find frequency of a character from a string
why the code doesn't work??为什么代码不起作用?? anything wrong with that loop??
那个循环有什么问题吗?? if then what should be answer?
如果那么应该回答什么? and why it can't be.
以及为什么不能。 Please make me clear.
请让我清楚。 :)
:)
#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;
}
please check this way.请检查这种方式。 you are matching letter 'k' instead of variable.
您正在匹配字母“k”而不是变量。
if(s[i]==k)
First use l = strlen(s)+1;
首先使用
l = strlen(s)+1;
instead of l = strlen(s);
而不是
l = strlen(s);
. . Then change
s[i]=0
in for loop to i = 0;
然后将for循环中的
s[i]=0
改为i = 0;
and use i<l
instead of s[i]<l
.并使用
i<l
而不是s[i]<l
。
Also, change if(s[i]=='k')
to if(s[i]==k)
.另外,将
if(s[i]=='k')
更改为if(s[i]==k)
。
Full example:完整示例:
#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;
}
The datatype of the variable l is char.It should be declared of the type int.变量 l 的数据类型是 char。它应该被声明为 int 类型。 You have initialised j with value 1 when it should have been initialised with 0 .
您已将 j 初始化为值 1 ,而本应使用 0 进行初始化。 The for loop is incorrect.
for 循环不正确。 Instead of s[i] use i and check the condition i < l .
而不是 s[i] 使用 i 并检查条件 i < l 。 And finally in the if condition replace 'k' by k I hope this will help you get desired result
最后在 if 条件下用 k 替换 'k' 我希望这会帮助你得到想要的结果
I can see you made many mistakes, I will list them up:我看你犯了很多错误,我把它们列出来:
The code example:代码示例:
#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.