【发布时间】:2016-01-28 18:38:10
【问题描述】:
下面的代码产生一个荒谬的输出 32674 用于计数 'aaa' 中的 'aa' 数量的测试输入。我该如何纠正这个问题?
#include<stdio.h>
#include<string.h>
int main()
{
int i,j,len ,k ,count, num ;
char str[100],sub[100],comp[100] ;
// sub is the sub string .
printf("Please enter the string") ;
fgets(str,sizeof(str),stdin) ;
printf("Enter the substring to be searched for") ;
fgets(sub,sizeof(str),stdin) ;
len=strlen(sub) ;
for ( i=0 ; i < (strlen(str) - len ); i++ )
/*Goes till length of string - length of sub string so that all
characters can be compared. */
{
num = i + len ;
for ( j=i,k=0 ; j<num ; j++, k++ )
//Loop to store each sub string in an array comp.
{
comp[k]=str[j] ;
}
comp[k+1]='\0' ;
/*A previous suggestion given : comp[k]
to be the null character but I dont see how/why? and that is
giving a similarly wrong output as well. */
if ( strcmp(comp,sub) == 0 )
{ count++ ; }
}
printf("no of occurances is:%d",count) ;
return 0 ;
}
【问题讨论】:
-
这并没有回答问题,但是如何使用 strstr 来查找子字符串?应该让事情变得更简单