1. 程式人生 > >字符串匹配

字符串匹配

pre aca back dex void right std ring blog

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<string.h>
 4 
 5 int Index_BF(const char *dst,const char *src,int pos)
 6 {
 7     int i=pos,j=0;
 8     while(dst[i+j]!=\0&&src[j]!=\0)
 9     {
10         if(dst[i+j]==src[j])
11         {
12 
13             j++;
14 } 15 else 16 { 17 i++; 18 j=0; 19 } 20 21 } 22 if(src[j]==\0) 23 return i; 24 else 25 return -1; 26 27 } 28 29 char *func() 30 { 31 const char *dst="aaacaaa"; 32 const char *src="aca";
33 const char *src2="a"; 34 char *str=""; 35 int src_len=strlen(src); 36 int left=0,right=0; 37 int index_left,index_right; 38 int index=Index_BF(dst,src,0); 39 if(index!=-1) 40 { 41 index_left=Index_BF(dst,src2,0); 42 index_right=Index_BF(dst,src2,index+src_len);
43 if(index_left!=-1&&index_left<index) 44 left=1; 45 if(index_right!=-1&&index_right>index+src_len-1) 46 right=1; 47 48 printf("index %d index_left %d index_right %d\n",index,index_left,index_right); 49 } 50 else 51 str="invalid"; 52 if(left==1&&right==0) 53 str="backward"; 54 else if(left==0&&right==1) 55 str="forward"; 56 else if(left==1&&right==1) 57 str="both"; 58 else 59 str="invalid"; 60 return str; 61 62 } 63 void main() 64 { 65 char *str=func(); 66 printf("func\n"); 67 printf("%s\n",str); 68 }

字符串匹配