Il modo più veloce per eseguire una ricerca di sottostringa senza distinzione tra maiuscole e minuscole in C / C ++?
-
03-07-2019 - |
Domanda
Nota ??h2>
La domanda che segue è stata posta nel 2008 su alcuni codici del 2003. Come mostra il aggiornamento del PO, questo intero post è stato obsoleto dagli algoritmi vintage 2008 e persiste qui solo come curiosità storica.
Ho bisogno di fare una veloce ricerca di sottostringhe senza distinzione tra maiuscole e minuscole in C / C ++. I miei requisiti sono i seguenti:
- Dovrebbe comportarsi come strstr () (ovvero restituire un puntatore al punto di corrispondenza).
- Non distingue tra maiuscole e minuscole (doh).
- Deve supportare le impostazioni internazionali correnti.
- Deve essere disponibile su Windows (MSVC ++ 8.0) o facilmente trasportabile su Windows (ovvero da una libreria open source).
Ecco l'implementazione attuale che sto usando (presa dalla GNU C Library):
/* Return the offset of one string within another.
Copyright (C) 1994,1996,1997,1998,1999,2000 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
/*
* My personal strstr() implementation that beats most other algorithms.
* Until someone tells me otherwise, I assume that this is the
* fastest implementation of strstr() in C.
* I deliberately chose not to comment it. You should have at least
* as much fun trying to understand it, as I had to write it :-).
*
* Stephen R. van den Berg, berg@pool.informatik.rwth-aachen.de */
/*
* Modified to use table lookup instead of tolower(), since tolower() isn't
* worth s*** on Windows.
*
* -- Anders Sandvig (anders@wincue.org)
*/
#if HAVE_CONFIG_H
# include <config.h>
#endif
#include <ctype.h>
#include <string.h>
typedef unsigned chartype;
char char_table[256];
void init_stristr(void)
{
int i;
char string[2];
string[1] = '\0';
for (i = 0; i < 256; i++)
{
string[0] = i;
_strlwr(string);
char_table[i] = string[0];
}
}
#define my_tolower(a) ((chartype) char_table[a])
char *
my_stristr (phaystack, pneedle)
const char *phaystack;
const char *pneedle;
{
register const unsigned char *haystack, *needle;
register chartype b, c;
haystack = (const unsigned char *) phaystack;
needle = (const unsigned char *) pneedle;
b = my_tolower (*needle);
if (b != '\0')
{
haystack--; /* possible ANSI violation */
do
{
c = *++haystack;
if (c == '\0')
goto ret0;
}
while (my_tolower (c) != (int) b);
c = my_tolower (*++needle);
if (c == '\0')
goto foundneedle;
++needle;
goto jin;
for (;;)
{
register chartype a;
register const unsigned char *rhaystack, *rneedle;
do
{
a = *++haystack;
if (a == '\0')
goto ret0;
if (my_tolower (a) == (int) b)
break;
a = *++haystack;
if (a == '\0')
goto ret0;
shloop:
;
}
while (my_tolower (a) != (int) b);
jin:
a = *++haystack;
if (a == '\0')
goto ret0;
if (my_tolower (a) != (int) c)
goto shloop;
rhaystack = haystack-- + 1;
rneedle = needle;
a = my_tolower (*rneedle);
if (my_tolower (*rhaystack) == (int) a)
do
{
if (a == '\0')
goto foundneedle;
++rhaystack;
a = my_tolower (*++needle);
if (my_tolower (*rhaystack) != (int) a)
break;
if (a == '\0')
goto foundneedle;
++rhaystack;
a = my_tolower (*++needle);
}
while (my_tolower (*rhaystack) == (int) a);
needle = rneedle; /* took the register-poor approach */
if (a == '\0')
break;
}
}
foundneedle:
return (char*) haystack;
ret0:
return 0;
}
Puoi rendere questo codice più veloce o conosci un'implementazione migliore?
Nota: ho notato che la libreria GNU C ora ha una nuova implementazione di strstr ()
, ma non sono sicuro quanto facilmente può essere modificato per non distinguere tra maiuscole e minuscole, o se in effetti è più veloce di quello vecchio (nel mio caso). Ho anche notato che la vecchia implementazione viene ancora utilizzata per stringhe di caratteri di grandi dimensioni , quindi se qualcuno sa perché, per favore condividi.
Aggiorna
Solo per chiarire le cose & # 8212; nel caso in cui non fosse già & # 8212; Non ho scritto questa funzione, fa parte della GNU C Library. L'ho modificato solo per distinguere tra maiuscole e minuscole.
Inoltre, grazie per il suggerimento su strcasestr ()
e per aver verificato altre implementazioni da altre fonti (come OpenBSD, FreeBSD, ecc.). Sembra essere la strada da percorrere. Il codice sopra è del 2003, motivo per cui l'ho pubblicato qui nella speranza che sia disponibile una versione migliore, che a quanto pare lo è. :)
Soluzione
Il codice che hai pubblicato è circa la metà più veloce di strcasestr
.
$ gcc -Wall -o my_stristr my_stristr.c
steve@solaris:~/code/tmp
$ gcc -Wall -o strcasestr strcasestr.c
steve@solaris:~/code/tmp
$ ./bench ./my_stristr > my_stristr.result ; ./bench ./strcasestr > strcasestr.result;
steve@solaris:~/code/tmp
$ cat my_stristr.result
run 1... time = 6.32
run 2... time = 6.31
run 3... time = 6.31
run 4... time = 6.31
run 5... time = 6.32
run 6... time = 6.31
run 7... time = 6.31
run 8... time = 6.31
run 9... time = 6.31
run 10... time = 6.31
average user time over 10 runs = 6.3120
steve@solaris:~/code/tmp
$ cat strcasestr.result
run 1... time = 3.82
run 2... time = 3.82
run 3... time = 3.82
run 4... time = 3.82
run 5... time = 3.82
run 6... time = 3.82
run 7... time = 3.82
run 8... time = 3.82
run 9... time = 3.82
run 10... time = 3.82
average user time over 10 runs = 3.8200
steve@solaris:~/code/tmp
La funzione main
era:
int main(void)
{
char * needle="hello";
char haystack[1024];
int i;
for(i=0;i<sizeof(haystack)-strlen(needle)-1;++i)
{
haystack[i]='A'+i%57;
}
memcpy(haystack+i,needle, strlen(needle)+1);
/*printf("%s\n%d\n", haystack, haystack[strlen(haystack)]);*/
init_stristr();
for (i=0;i<1000000;++i)
{
/*my_stristr(haystack, needle);*/
strcasestr(haystack,needle);
}
return 0;
}
È stato opportunamente modificato per testare entrambe le implementazioni. Noto mentre lo sto scrivendo ho lasciato nella chiamata init_stristr
, ma non dovrebbe cambiare troppo le cose. bench
è solo un semplice script shell:
#!/bin/bash
function bc_calc()
{
echo $(echo "scale=4;$1" | bc)
}
time="/usr/bin/time -p"
prog="$1"
accum=0
runs=10
for a in $(jot $runs 1 $runs)
do
echo -n "run $a... "
t=$($time $prog 2>&1| grep user | awk '{print $2}')
echo "time = $t"
accum=$(bc_calc "$accum+$t")
done
echo -n "average user time over $runs runs = "
echo $(bc_calc "$accum/$runs")
Altri suggerimenti
È possibile utilizzare la funzione StrStrI che trova la prima occorrenza di una sottostringa all'interno di una stringa. Il confronto non fa distinzione tra maiuscole e minuscole. Non dimenticare di includere la sua intestazione - Shlwapi.h. Dai un'occhiata a: http: // msdn.microsoft.com/en-us/library/windows/desktop/bb773439(v=vs.85).aspx
Per uso indipendente dalla piattaforma:
const wchar_t *szk_wcsstri(const wchar_t *s1, const wchar_t *s2)
{
if (s1 == NULL || s2 == NULL) return NULL;
const wchar_t *cpws1 = s1, *cpws1_, *cpws2;
char ch1, ch2;
bool bSame;
while (*cpws1 != L'\0')
{
bSame = true;
if (*cpws1 != *s2)
{
ch1 = towlower(*cpws1);
ch2 = towlower(*s2);
if (ch1 == ch2)
bSame = true;
}
if (true == bSame)
{
cpws1_ = cpws1;
cpws2 = s2;
while (*cpws1_ != L'\0')
{
ch1 = towlower(*cpws1_);
ch2 = towlower(*cpws2);
if (ch1 != ch2)
break;
cpws2++;
if (*cpws2 == L'\0')
return cpws1_-(cpws2 - s2 - 0x01);
cpws1_++;
}
}
cpws1++;
}
return NULL;
}
Perché usi _strlwr (stringa); in init_stristr ()? Non è una funzione standard. Presumibilmente è per il supporto locale, ma poiché non è standard, userei solo:
char_table[i] = tolower(i);
usa boost algo string . È disponibile, multipiattaforma e solo un file di intestazione (nessuna libreria per il collegamento). Per non parlare del fatto che dovresti comunque utilizzare boost.
#include <boost/algorithm/string/find.hpp>
const char* istrstr( const char* haystack, const char* needle )
{
using namespace boost;
iterator_range<char*> result = ifind_first( haystack, needle );
if( result ) return result.begin();
return NULL;
}
Ti consiglio di prendere alcune delle implementazioni di strcasestr comuni già esistenti. Ad esempio di glib, glibc, OpenBSD, FreeBSD, ecc. Puoi cercare di più con google.com/codesearch. È quindi possibile effettuare alcune misurazioni delle prestazioni e confrontare le diverse implementazioni.
Supponendo che entrambe le stringhe di input siano già in minuscolo.
int StringInStringFindFirst(const char* p_cText, const char* p_cSearchText)
{
int iTextSize = strlen(p_cText);
int iSearchTextSize = strlen(p_cSearchText);
char* p_cFound = NULL;
if(iTextSize >= iSearchTextSize)
{
int iCounter = 0;
while((iCounter + iSearchTextSize) <= iTextSize)
{
if(memcmp( (p_cText + iCounter), p_cSearchText, iSearchTextSize) == 0)
return iCounter;
iCounter ++;
}
}
return -1;
}
Potresti anche provare a usare le maschere ... se per esempio la maggior parte delle stringhe che stai per confrontare contiene solo caratteri dalla a alla z, forse vale la pena fare qualcosa del genere.
long GetStringMask(const char* p_cText)
{
long lMask=0;
while(*p_cText != '\0')
{
if (*p_cText>='a' && *p_cText<='z')
lMask = lMask | (1 << (*p_cText - 'a') );
else if(*p_cText != ' ')
{
lMask = 0;
break;
}
p_cText ++;
}
return lMask;
}
Quindi ...
int main(int argc, char* argv[])
{
char* p_cText = "this is a test";
char* p_cSearchText = "test";
long lTextMask = GetStringMask(p_cText);
long lSearchMask = GetStringMask(p_cSearchText);
int iFoundAt = -1;
// If Both masks are Valid
if(lTextMask != 0 && lSearchMask != 0)
{
if((lTextMask & lSearchMask) == lSearchMask)
{
iFoundAt = StringInStringFindFirst(p_cText, p_cSearchText);
}
}
else
{
iFoundAt = StringInStringFindFirst(p_cText, p_cSearchText);
}
return 0;
}
Questo non prenderà in considerazione le impostazioni locali, ma se puoi modificare IS_ALPHA e TO_UPPER puoi farlo considerare.
#define IS_ALPHA(c) (((c) >= 'A' && (c) <= 'Z') || ((c) >= 'a' && (c) <= 'z'))
#define TO_UPPER(c) ((c) & 0xDF)
char * __cdecl strstri (const char * str1, const char * str2){
char *cp = (char *) str1;
char *s1, *s2;
if ( !*str2 )
return((char *)str1);
while (*cp){
s1 = cp;
s2 = (char *) str2;
while ( *s1 && *s2 && (IS_ALPHA(*s1) && IS_ALPHA(*s2))?!(TO_UPPER(*s1) - TO_UPPER(*s2)):!(*s1-*s2))
++s1, ++s2;
if (!*s2)
return(cp);
++cp;
}
return(NULL);
}
Se vuoi eliminare i cicli della CPU, potresti considerare questo: supponiamo che abbiamo a che fare con ASCII e non con Unicode.
Crea una tabella statica con 256 voci. Ogni voce nella tabella è di 256 bit.
Per verificare se due caratteri sono uguali, fai qualcosa del genere:
if (BitLookup(table[char1], char2)) { /* match */ }
Per costruire la tabella, devi impostare un po 'ovunque nella tabella [char1] dove la consideri una corrispondenza per char2. Quindi, nella costruzione della tabella, dovresti impostare i bit nell'indice per "a" e "A" nella voce "a" (e nella voce "A").
Ora sarà un po 'lento eseguire la ricerca dei bit (la ricerca dei bit sarà uno spostamento, maschera e aggiunta molto probabilmente), quindi potresti usare invece una tabella di byte in modo da usare 8 bit per rappresentare 1 bit. Ci vorranno 32K - quindi evviva - hai raggiunto un compromesso tempo / spazio! Potremmo voler rendere il tavolo più flessibile, quindi diciamo che lo facciamo invece - il tavolo definirà invece le congruenze.
Due caratteri sono considerati congruenti se e solo se esiste una funzione che li definisce equivalenti. Quindi 'A' e 'a' sono congruenti per l'insensibilità al caso. 'A', 'À', 'Á' e 'Â' sono congruenti per l'insensibilità diacritica.
Quindi definisci bitfield corrispondenti alle tue congruenze
#define kCongruentCase (1 << 0)
#define kCongruentDiacritical (1 << 1)
#define kCongruentVowel (1 << 2)
#define kCongruentConsonant (1 << 3)
Quindi il tuo test è qualcosa del genere:
inline bool CharsAreCongruent(char c1, char c2, unsigned char congruency)
{
return (_congruencyTable[c1][c2] & congruency) != 0;
}
#define CaseInsensitiveCharEqual(c1, c2) CharsAreCongruent(c1, c2, kCongruentCase)
Questo tipo di armeggiare con tavoli enormi è il cuore del tipo, a proposito.
Se riesci a controllare la stringa dell'ago in modo che sia sempre in minuscolo, puoi scrivere una versione modificata di stristr () per evitare le ricerche per quello, e quindi accelerare il codice. Non è così generale, ma può essere più veloce, leggermente più veloce. Commenti simili si applicano al pagliaio, ma è più probabile che tu stia leggendo il pagliaio da fonti al di fuori del tuo controllo in quanto non puoi essere certo che i dati soddisfino il requisito.
Se vale il guadagno in termini di prestazioni, è un'altra domanda del tutto. Per il 99% delle domande, la risposta è "No, non ne vale la pena". L'applicazione potrebbe essere una delle minuscole minoranze in cui è importante. Più probabilmente, non lo è.