int find_substr(char* str,char* sub_str){
int index = 0;
while(*str!='\0'){
if(*str != *sub_str){
str++;
index++;
continue;
}
// 创建临时指针进行查找
char* temp_str = str;
char* temp_substr = sub_str;
while(*temp_substr != '\0'){
if(*temp_str != *temp_substr){
// 匹配失败情况
str++;
index++;
break;
}
// 临时指针匹配相同情况
temp_str++;
temp_substr++;
}
if(*temp_substr == '\0'){
// 匹配成功
return index;
}
}
return -1;
}
int main(void){
char s[] = "abcdefgQAQasd";
int index = find_substr(s,"QAQ");
if(index!=-1){
printf("sub_str index: %d",index);
}else{
printf("not found!");
}
return 0;
}
查找目标子串在原串中位置 C语言
最新推荐文章于 2023-12-04 21:28:52 发布