查找字符串中的子字符串数

下面的代码产生了一个荒谬的输出32674,用于’aaa’中计数’aa’的测试输入。 我该如何纠正这个?

#include #include 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 ; } 

count未初始化,因此count的打印值无效。

 int i,j,len ,k ,count, num ; count = 0; // add ... { count++ ; } ... printf("no of occurances is:%d",count) ; 

建议从输入结尾删除潜在的\n

 fgets(str, sizeof str ,stdin); str[strcspn(str, "\n")] = '\0'; // add 

可能存在其他问题: @dbush

两个问题:

fgets读取换行符并将其添加到读入的字符串中。您需要将其删除:

 if (str[strlen(str)-1] == '\n') str[strlen(str)-1]='\0'; ... if (sub[strlen(sub)-1] == '\n') sub[strlen(sub)-1]='\0'; 

在构建要比较的子字符串时,您将空终止符放在一个太远的空格中:

 comp[k+1]='\0' ; 

在循环退出之前k已经递增,所以不需要添加1:

 comp[k]='\0' ;