字符串匹配
朴素的字符串匹配
挨个扫描就完了,简直太他妈朴素了,就这我还没写出来,看了之后手法还是很精妙的
#include<iostream>
using namespace std;
int StrLen(const char* str){
const char* p = str;
int i = 0;
while(*p){
i++;
p++;
}
return i;
}
const char* StrStr(const char* str1,const char* str2){
if(str2 == NULL){
return NULL;
}
const char* p = str1;
while(*p){
const char* p1 = p;
const char* p2 =str2;
while(*p1 && *p2 && (*p1 == *p2)){
p1++;
p2++;
}
if(!*p2){
return p; //这里返回的实际上是源串的匹配好的字串,可能含有多余字符
} //如str1为mengziyue,str2为zi,这时返回的是ziyue
p++;
}
return NULL;
}
int StrForLoop(const char* str1,const char* str2){
int str1_len = StrLen(str1);
int str2_len = StrLen(str2);
int max_len = str1_len - str2_len;
for(int i = 0;i < max_len;i++){
int match_len = 0;
while(match_len < str2_len && str1[i+match_len] == str2[match_len]
){
match_len++;
}
if(match_len == str2_len){
return i;
}
}
return -1;
}
int main(){
const char* str1 = "xiandianzikejidaxue";
const char* str2 = "keji";
const char* str3 = StrStr(str1,str2);
cout<<str3<<endl;
cout<<StrForLoop(str1,str2)<<endl;
return 0;
}
原文地址:https://www.cnblogs.com/ziyuemeng/p/12393254.html
时间: 2024-10-01 15:38:18