【发布时间】:2016-01-27 14:00:16
【问题描述】:
下面的代码总是返回匹配子字符串的数量为零。代码中没有错误,我不确定我在逻辑上哪里出错了。
#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") ;
gets(str) ;
printf("Enter the substring to be searched for") ;
gets(sub) ;
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] ;
}
if ( strcmp(comp,sub) == 0 )
{ count++ ; }
}
printf("no of occurances is:%d",count) ;
return 0 ;
}
【问题讨论】:
-
这段代码没有任何意义。为什么首先需要复制子字符串?
-
除非有很好的理由,否则使用 fgets 而不是 gets。
-
使用调试器或至少打印您检查的数据。
-
@ForeverStudent:哪个原因会纠正使用没有更多功能的不安全功能?
-
@Olaf:我们以前都听过的愚蠢的:赋值不允许 fgets,我们的自定义编译器/运行时不支持 fgets,等等