【C++ 从较长字符串str1找较短字符串str2出现的次数】

【问题】
不知道为什么我的代码中间出现的str2无法计算在内,求大神帮找代码问题:
【代码如下】

#include <iostream>
#include <cstdio>
#include <cmath>

using namespace std;
int main(){
    
    string str1 = "";
    string str2 = "";
    
    cout << "请输入第一个较长字符串:" << endl;
    getline(cin, str1);
    cout << "请输入第二个子字符串:" << endl;
    getline(cin, str2);
    //cout << str1 << endl;
    //cout << str2 << endl;
    
    int length1 = str1.length();
    int length2 = str2.length();
    //cout << length1 << " " << length2 << endl;
    
    int count = 0;  // 计数 
    // 遍历较长字符串 
    for(int i = 0; i < length1 - 1;i++){
        // 先找到首字符相同位置 
        if (str2[0] == str1[i]){
            // 应该先判断后续长度是否足够
            if ((i + length2 - 1) <= length1 - 1){
                // 注意切片取前不取后 
                if (str1.substr(i,i + length2) == str2){
                    count += 1;
                    // 修改下标,注意最后一段恰好相同的情况 
                    if ((i + length2 - 1) == length1 - 1){
                        i = length1 - 1;
                    }
                    else{
                        i = i + length2;
                    }
                }
            }
        }
    } 
    
    cout << "出现次数为:" << count << endl;
    return 0; 
} 

img

主要是你substr函数用错了,第二个参数表示要截取的长度,不是截取到的结束位置
if (str1.substr(i,i + length2) == str2){
改为:
if (str1.substr(i,length2) == str2){
就好了



#pragma warning(disable:4996)

#include<stdio.h> 
bool Contains(const char* p, const char* t,int & index) {
    bool flag = false;
    const char* s = t;
    index = -1;
    while (*p != '\0' && *t != '\0') {
        *p == *t ?  t++, p++
            : t != s ? (index--),t = s :
            p++,(index++);
    }
    if (*t == '\0') {
        flag = true;
    }
    return flag;
}
int main() {
    const char * first = "AABAACAA";
    const char* second = "AAC";
    int count = 0;
    while (*first != '\0') {
        int index = 0;
        bool flag = Contains(first, second, index);
        if (index == -1) {
            break;
        }
        else {
            if(flag)
            count++;
        }
        for (int i = 0; i < index + 1; i++) {
            first++;
        }
    }
    printf("%d", count);

}

如果要按照题主的写法
要对字符串用strcmp来做相等 不能直接==

之前写过一个函数,参考:

//查找big串中所有smal串的位置,并把位置存放在pos中,nmb存放个数
void findstr(char*big ,char* smal,int pos[],int *nmb)
{
    int i,j,lenb,lens;
    lenb = strlen(big);
    lens = strlen(smal);
    *nmb = 0;
    if(lens > lenb)
        return;
    
    i = 0;
    while(i < lenb-lens+1)
    {
        for (j = 0; j < lens;j++)
        {
            if(tolower(big[i+j]) != tolower(smal[j]))
                break;
        }
        if (j == lens) //说明找到
        {
            pos[*nmb] = i;
            (*nmb)++;
            i += lens;
        }else
            i++;
    }
}