【问题标题】:Find number of sub strings in a string查找字符串中的子字符串数
【发布时间】: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 来查找子字符串?应该让事情变得更简单

标签: c string loops


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    两个问题:

    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' ;
    

    【讨论】:

    • 如果输入不常见,str[strlen(str)-1] 可能会导致 UB。建议stackoverflow.com/a/28462221/2410359
    • fgets 总是以空值终止它填充的字符串,因此在fgets 之后立即使用上述内容应该很好地定义。
    • fgets() 读取直到遇到'\n'。如果第一个字符是'\0',它不会停止读取。通过fgets() 输入空字符是一种黑客攻击,因为它会导致str[strlen(str)-1] --> str[-1]strlen() 停在第一个空字符上,不一定是 fgets() 附加的那个,正如您正确评论的那样。
    猜你喜欢
    • 2012-02-21
    • 2012-09-07
    • 2011-07-13
    • 2013-10-22
    • 2021-08-13
    • 2015-10-28
    • 2017-12-04
    相关资源
    最近更新 更多