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

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

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

#include <iostream>
#include <cstring>
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......
    char *s1=str,*s2=substr,*s3;//利用指针
    while(*s1!='\0'){
        s3=s1;//s3用来记录str的起始点
        while(*s2!='\0'){
            if(*s3!=*s2) break;//若没有匹配上,则直接跳出
            else {s3++;s2++;}//若匹配上,继续往下一位匹配
        }
        if(*s2=='\0') count++;//如果s2到末尾,则代表s2已经全部匹配上了
        s2=substr;//s2回到子串的开头
        s1++;//s1向下一个字符走
        

    }


    cout << count << endl;

    return 0;
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务