MM said:
Hello there
I need a way to efficiently check if a string I specify can be found in
another string.
For example, if I look for the string "searchString" in the string "jlh ahs
dalskd" then it is of course NOT found, but if I instead look for the same
string in "lkasjalskj searchString sedlfksd" then it IS found.
So, is there any (fairly) efficient way to do this?
The C language Standard makes no guarantees -- indeed,
it says nothing at all -- about the efficiency of any
construct or library function. Still, a few guidelines:
- If you're doing just a few such searches, use
the strstr() function
- If you're doing many searches using the same
"SearchString" in different target strings,
implement something like the Bayer-Moore
algorithm
- If you're doing many searches using different
"SearchString"s in the same target string,
implement something like Patricia (see Knuth
TAOCP Volume III)
- If you're doing many searches using different
"SearchStrings" *and* different target strings,
use the strstr() function
.... but in no case should you go to the effort of Bayer-Moore
or Patricia until you've *measured* your program's performance
and *proven* to yourself that searching for strings within
strings takes unacceptably long. Start with strstr() and
adopt fancier solutions only if they're proven necessary --
and even then, it might turn out that the "best" approach
is to re-think the program design to obviate the searches.