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

编程入门 行业动态 更新时间:2024-10-24 15:23:35
本文介绍了查找字符串中子字符串的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

下面的代码为"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

更多推荐

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

本文发布于:2023-10-19 14:53:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1507854.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   中子   数量

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!