CPP33. 统计字符串中子串出现的次数
描述
键盘输入两个字符串 str 和 substr,统计字符串 substr 在 字符串 str 中出现的次数,并输出。输入描述
键盘输入两个长度小于 100 的字符串 str 和 substr输出描述
输出字符串 substr 在 字符串 str 中出现的次数示例1
输入:
nihaohellowoshihello hello
输出:
2
C++ 解法, 执行用时: 2ms, 内存消耗: 396KB, 提交时间: 2022-01-26
#include <iostream> #include <cstring> using namespace std; bool compare(char str[],char substr[],int start){ for(int i=0;i<strlen(substr);i++){ if(str[start+i] != substr[i]) return false; } return true; } 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;i<strlen(str);i++){ if(str[i]==substr[0]){ if(compare(str,substr,i)==true) count++; } } cout << count << endl; return 0; }
C++ 解法, 执行用时: 2ms, 内存消耗: 396KB, 提交时间: 2021-12-31
#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,i; // write your code here...... char *p,* q; p=str; q= substr; while(*p!='\0') { if(*p==*q) { p = p+1; q = q+1; if(*q=='\0') { count++; q= substr; p= str +i; } } else { p = p+1; q= substr; } i++; } cout << count << endl; return 0; }
C++ 解法, 执行用时: 2ms, 内存消耗: 396KB, 提交时间: 2021-12-20
#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;i<strlen(str)-strlen(substr)+1;i++){ if(strncmp(str+i,substr,strlen(substr))==0)count++; } cout << count << endl; return 0; }
C++ 解法, 执行用时: 2ms, 内存消耗: 396KB, 提交时间: 2021-11-24
#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 m=sizeof(str)/sizeof(str[0]); int n=sizeof(substr)/sizeof(substr[0]); for(int i = 0; i<m; i++) { bool flag = true; for(int j = 0; substr[j] != '\0'; j++) { if(str[i + j] != '\0' && str[i + j] == substr[j]) { continue; } else { flag = false; //不相同,这一次不是子串 break; } } if(flag) count++; } cout << count << endl; return 0; }
C++ 解法, 执行用时: 2ms, 内存消耗: 396KB, 提交时间: 2021-11-20
#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; int j; int size = strlen(substr); while(str[i]!='\0') { j = 0; if(str[i]==substr[j]) { while(substr[j]!='\0') { if(substr[j] ==str[i+j]) j++; else break; } if(j ==size) count++; } i++; } cout << count << endl; return 0; }