here is a general implementation
int stridx (char[] src, char[] str){
int i,j,k;
for(i=0;i < (src.len - str.len);i++){
for(j=i,k=0; str[k] != '\0' && str[k] == src[i]; j++,k++);
if( k> 0 && str[k]=='\0') return i;
}
return -1;
}
The worst case of the algorithm could be n^2, if we have aaaaaaaaaaaaaaaaaaaaaaaa (assuming both src and str are very long, and the length of them is very close).
Can I have a better algorithm?
You could use the Boyer-Moore algorithm, which is O(n). Here's sample C code.
It's not necessary to calculate the length of the strings :
char *strr(char *s1,char *s2)
{
int i,j;
for(i=0;s1[i];i++)
if(s1[i]==s2[0])
for(j=0;s1[i+j]==s2[j];j++)
if(!s2[j+1]) return &s1[i];
return NULL;
}
http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm is another linear time algorithm. OTOH, the simple algorithms stay because in practise they are faster for most of the strings people actually search with.
精彩评论