题解 | #统计字符串中子串出现的次数#
统计字符串中子串出现的次数
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......
	int i = 0, j = 0;//i记录主字符串下表 j记录子字符串
    int sublen = strlen(substr);
    while (str[i] != '\0') {
        for (j = 0; j < sublen; j++) {
            if (str[i+j] != substr[j]) {
                break;
            }
        }
		//这个部分不会判断重复的字符串 比如aaa中算作出现两次aa
		//所以改用上面的for循环
		// if (str[i] == substr[j]) {
        //     j++;
        // } else {
        //     j = 0;
        // }
        if (j == sublen) {
            j = 0;
            count++;
        }      
        i++;
    }
    cout << count << endl;
    return 0;
}
查看7道真题和解析