子串查詢函式strstr

鍾超發表於2010-04-24

/************************ * Project Name : String Operation Functions * Module Name : Strstr.c * Create : 2010-04-24(Sat) * Update : 2010-04-24(Sat) * Copyright : Micheal Zhong * Reference : ************************/ #include<stdio.h> int strstr( char *master, char *slave ) { char *m = master; char *s = slave; int count = 0; int temp = 0; while( *m != '/0' )//go to the tail of the master { while( *m != '/0' && *m != *s ) //find the first char of slave in master { m++; count++;//count addition follows m } if( m == '/0' ) //do not exist the first char of slave in master printf("DO NOT EXIST! CUP!/n"); else temp = count; //exist the first char of slave in master //save its position to temp while( *m == *s && *s != '/0' && *m != '/0' ) //compare slave and master until m != s //or get the end of master or slave { m++; count++;//count addition follows m s++; } if( *s == '/0' ) //get the end of slave //which means slave exists in master { return temp; //output the position of the slave's head in master if( *m == '/0' ) //get the end of master exit(0); else s = slave; //maybe slave appears more than one time in master } else if( *m == '/0' )//get the end of slave, then halt { printf( "DO NOT EXIST! CUP!/n" ); exit(0); } else if( *m != *s ) //The slave's head is similar to the master's substring //but do not match { s = slave; m = master + temp + 1; count = temp + 1; } } }

相關文章