Match beginning of two strings

Jim Richardson warlock at eskimo.com
Sun Aug 3 09:22:14 CEST 2003


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On Sun, 3 Aug 2003 00:22:46 -0600,
 Andrew Dalke <adalke at mindspring.com> wrote:
> 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.
> 
>

Why bother finding out which one is the shorter? if you try the compare,
and you run out of the other to compare to, then by default, it's not
the same :)  


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.2 (GNU/Linux)

iD8DBQE/LLgmd90bcYOAWPYRAoWbAJ9dgt4IMuu07FgyuUAtdJlVf5AWygCg1Rek
7Qd4Z6xgK1NwhysngVlLQY0=
=ZWGw
-----END PGP SIGNATURE-----

-- 
Jim Richardson         http://www.eskimo.com/~warlock

Linux, because eventually, you grow up enough to be trusted with a fork()




More information about the Python-list mailing list