Match beginning of two strings

Andrew Dalke adalke at mindspring.com
Sun Aug 3 08:22:46 CEST 2003


Ravi:
> Read in both strings.
> Check to see if the first character matches.
> If yes:
>      Check halfway through the string and see if that character matches
>      Repeatedly check halfway until the difference point is found.
>      Go back through from the difference point backwards and make sure
> the characters match from the start to the difference point.
>
> I timed it, and it seems to be doing about 3.5usec per loop.

There's a lot of overhead for doing that.  Have you tried the simple

char *s1 = ... the first string ..
char *s2 = ... the second string ..
n = ... the shorter of the two ..
for(i=0; i<n; i++) {
  if (*s1++ != *s2++) {
    break;
  }
}
return ... the string s1[:n] (or even just the int)

Easy to understand, and the CPU is spending almost its whole
time doing character tests.

                    Andrew
                    dalke at dalkescientific.com






More information about the Python-list mailing list