题解 | #统计字符串中子串出现的次数#
统计字符串中子串出现的次数
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...... for (int i = 0,j = 0; i < strlen(str); i++){ if (str[i] == substr[j]){//判断是否满足等于条件,如果满足子符串开始移动 j++; } else {//如果没有满足,则判断是否进行过子字符串移动操作,如果有,则将子字符索引回到初始值,并回退主字符串 if(j > 0){ i = i - j;//主字符串退回刚开始的字符 j = 0; } } if (j == strlen(substr)){ count++; i = i - j + 1;//主字符串退回刚开始的字符 + 1 j = 0; } } cout << count << endl; return 0; }