Valhalla Legends Forums Archive | C/C++ Programming | Function similar to strstr

AuthorMessageTime
Mephisto
Is there a function which searches a string for a string like strstr, but an additional requirement for it to return true is that it needs to be a complete word?

Examples:
strstr("Sargera[cS"], "Sargera"); // would return true
MyStrStr("Sargera[cS]", "Sargera"); // would return false

strstr("Blah was banned by Sargera[cS]", "Sargera"); // would return true;
// mine would return false

The point is, it returns false if it's not a complete word (e.g. two spaces on each side) or if it's not even there at all, and returns true if it's there and is a complete word.
December 27, 2004, 1:09 AM
Kp
// As a first pass, this ought to work fine.

[code]bool mss(const char *haystack, const char *needle) {
char *r = strstr(haystack, needle);
return r && r > haystack && r[-1] == ' ' && r[strlen(needle)] == ' ';
}[/code]
December 27, 2004, 1:28 AM
Mephisto
Thanks; your implementation is a lot cleaner than where I was going with it, lol.

Just had to make a slight modification to check for a period at the end (the whole point of this if I didn't mention already was to avoid adding users the bot didn't ban to the banlist) and to avoid a crash if it returned NULL:
[code]bool strdstr(const char *haystack, const char *needle)
{
char *r = strstr(haystack, needle);
if (r == NULL)
return FALSE;
else
return r && r > haystack && r[-1] == ' ' && r[strlen(needle)] == ' ' || r[strlen(needle)] == '.';
}[/code]
December 27, 2004, 1:36 AM
Kp
Yours is inefficient and buggy.  My code already checked for null by doing "r && <tests>".  If r had been NULL (0), the short-circuit would immediately return false.  Your change broke that logic because && has higher precedence than ||, so the compiler reads it as return (r && r > haystack && r[-1] == ' ' && r[strlen(needle)] == ' ') || (r[strlen(needle)] == '.').  A revised version, to correct your deficiencies:

[code]bool mss(const char *haystack, const char *needle) {
char *r = strstr(haystack, needle);
uint32_t l;
return r && r > haystack && r[-1] == ' ' && (r[l = strlen(needle)] == ' ' || r[l] == '.');
}[/code]
December 27, 2004, 4:49 AM
Eibro
Even better would be to check for ispunct && isspace.
December 27, 2004, 4:53 AM
Adron
But he wants to treat different characters separately... Aren't [()! punctuation?
December 27, 2004, 8:15 AM

Search