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

详见:
https://www.nowcoder.com/practice/9eb684f845a446f3b121472de2ea75cd?tpId=225&tags=&title=&difficulty=0&judgeStatus=0&rp=0

利用find函数

  • 首先将字符数组转化为字符串str1和str2。
  • 从str1下标i开始查找str2,如果找得到,计数加1,并且i从找到的位置,后移一位。
#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......
    string str1(str);
    string str2(substr);
    int i = 0;
    // str1.find(str2, i) == -1表示没有找到子串
    while (str1.find(str2, i) != -1){ 
        count++;
        i = str1.find(str2,i) + 1;
    }
    

    cout << count << endl;

    return 0;
}

双循环

可以遍历字符串str,直到’\0’结束。对于每个字符,我们以其为字符串头部,与substr同时遍历,要么遍历到substr结尾的’\0’,二者都遍历substr的长度,要么遍历到str的结尾,我们比较每个字符,如果整个比较都相同,则找到了子串,计数+1,只要有一个字符不同,则不是子串。

时间复杂度:O(mn),其中m为字符串str的长度,n为字符串substr的长度,遍历对于字符串str每个字符都要遍历字符串substr的长度
空间复杂度:O(1),无额外空间

#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......
    for(int i=0; str[i]!='\0'; i++){ //遍历字符数组str
        bool flag = true;
        for(int j=0; substr[j]!='\0'; j++){ //以字符数组str的i位置为起点,每次同步遍历substr长度
            if(str[i+j] != '\0' && str[i+j]==substr[j]) //比较每个字符
                continue;
            else{
                flag = false; // 一旦不相同,这一次不是子串
                break;
            }
        }
        if(flag)
            count++;
    }
    
    cout << count << endl;

    return 0;
}
  • 4
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值