Match beginning of two strings

Mañungo manuel at ortega.cl
Fri Aug 22 02:51:57 EDT 2003


"Andrew Dalke" <adalke at mindspring.com> wrote in message news:<bgi9g8$dc0$1 at slb6.atl.mindspring.net>...
> 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

First, I'm not a python programmer... but I think is better test int.
Something like that:

	int *a = (int *) ...first string...;
	int *b = (int *) ...second string...;

	for( i = 0; i < n; i += 4 )
	  if( *a++ != *b++ )
	    break;
	char *aa = (char *) a;
	char *bb = (char *) b;
	if( *aa++ == *bb++ ) i++;
	if( *aa++ == *bb++ ) i++;
	if( *aa == *bb ) i++;

and return i.




More information about the Python-list mailing list