查找字符串中子字符串的数量 [英] Find number of sub strings in a string

查看:211
本文介绍了查找字符串中子字符串的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码为"aaa"中计数为"aa"的测试输入生成了一个荒谬的输出32674.我该如何解决这个问题?

The below code produces a ridiculous output of 32674 for a test input of counting number of 'aa' in 'aaa'. How do i go about correcting this?

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

推荐答案

count未初始化,因此count的打印值没有用.

count is not initialized, so the printed value of count is not useful.

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

建议从输入末尾删除电位\n.

Suggest removing a potential \n from the end of input.

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

可能存在其他问题: @dbush

这篇关于查找字符串中子字符串的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆