题解 | #统计字符串中子串出现的次数#

统计字符串中子串出现的次数

http://www.nowcoder.com/practice/9eb684f845a446f3b121472de2ea75cd

#include #include using namespace std;

int main() {

char str[100] = { 0 };
char substr[100] = { 0 };

cin.getline(str, sizeof(str));
cin.getline(substr, sizeof(substr));

int count = 0;

// write your code here......
int flag;
int i=0;
while(i<strlen(str)){
    flag=0;
    if(str[i]==substr[0]){
        for(int j=0;j<strlen(substr);j++){
            if(str[i+j]!=substr[j]){
                flag=1;
            }
        }
        if(flag==0){
            count++;
            i=i+strlen(substr)-1;
        }
        else{
            i++;
        }
    }else{
        i++;
    }
}

cout << count << endl;

return 0;

}

全部评论
代码有一个错误, i=i+strlen(substr)-1; 意思是第二轮判断的起始点是上一次判断结束的子字符串结束的位置(也就是第一个hello结束的o的位置后面),但如果字符是有重叠的,比如字符串是nmmmmm,子字符串是mmm,就会出现少数的问题。
点赞 回复 分享
发布于 2023-03-08 20:36 上海

相关推荐

2025-12-18 11:24
山西大学 测试工程师
A_SOUL_Off...:疑似加班加出幻觉了
点赞 评论 收藏
分享
评论
4
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务