字符串中子串的查找
时间:2010-08-07 来源:wsnhyjj
写了个简单的程序完成字符串中子串的查找,可以返回字串在母串中的所有位置。
#include <stdio.h>
#include <stdlib.h>
int location[10],num=0;
void strstr(char *src,char*sub){ char *orig =src; char *p,*q; int sub_len=0;
if(src==NULL||sub==NULL) return; q=sub; while(*q++!='\0') sub_len++;
mark: while(*src){ p=src; q=sub; do{ if(!*q){ location[num++]=src-orig; src+=sub_len; goto mark; } }while(*p++==*q++); src++; }
}
int main(){ char *src; char *sub; int i;
src=(char*)malloc(50); sub=(char*)malloc(8);
printf("Please input the src string : "); gets(src); printf("\n"); printf("Please input the sub string : "); gets(sub); printf("\n");
strstr(src,sub);
for(i=0;i<num;i++){ printf("Location of sub string in src is %d. \n",location[i]); } return 0; }
int location[10],num=0;
void strstr(char *src,char*sub){ char *orig =src; char *p,*q; int sub_len=0;
if(src==NULL||sub==NULL) return; q=sub; while(*q++!='\0') sub_len++;
mark: while(*src){ p=src; q=sub; do{ if(!*q){ location[num++]=src-orig; src+=sub_len; goto mark; } }while(*p++==*q++); src++; }
}
int main(){ char *src; char *sub; int i;
src=(char*)malloc(50); sub=(char*)malloc(8);
printf("Please input the src string : "); gets(src); printf("\n"); printf("Please input the sub string : "); gets(sub); printf("\n");
strstr(src,sub);
for(i=0;i<num;i++){ printf("Location of sub string in src is %d. \n",location[i]); } return 0; }
相关阅读 更多 +