查找S串中第一次出现T串的位置
#include<stdio.h>
#include<string.h>
int fun(char s[],char t[]){
int i=0,j=0;
int Slen = strlen(s);
int Tlen = strlen(t);
while(i<Slen&&j<Tlen){
if(s[i]==t[j]) {
i++;
j++;
}
else{
i=i-j+1;
j=0;
}
}
if(j==Tlen){
return i-Tlen;
}
return -1;
}
int main(){
char s[] = "56123456789";
char t[] = "567";
int index = fun(s,t);
if(index!=-1)
printf("t串在s串的第%d个位置\n",index);
else
printf("t串在不是s串的子串\n");
return 0;
}
计算S串中出现T串的次数
#include<iostream>
#include<string.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
int Mystr(string s,string t){
int len1 = s.size();
int len2 = t.size();
int i = 0;
int j = 0;
int num = 0;
while(i<len1 && j<len2){
if(s[i]==t[j]){
i++;
j++;
}else{
i = i-j+1;
j=0;
}
if(j==len2){
num++;
j = 0;
}
}
return num;
}
int main(){
string s = "123452345";
string t = "345";
cout<<Mystr(s,t)<<endl;
return 0;
}