Valhalla Legends Archive

Programming => General Programming => C/C++ Programming => Topic started by: Mephisto on December 26, 2004, 07:09 PM

Title: Function similar to strstr
Post by: Mephisto on December 26, 2004, 07:09 PM
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.
Title: Re: Function similar to strstr
Post by: Kp on December 26, 2004, 07:28 PM
// As a first pass, this ought to work fine.

bool mss(const char *haystack, const char *needle) {
char *r = strstr(haystack, needle);
return r && r > haystack && r[-1] == ' ' && r[strlen(needle)] == ' ';
}
Title: Re: Function similar to strstr
Post by: Mephisto on December 26, 2004, 07:36 PM
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:
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)] == '.';
}
Title: Re: Function similar to strstr
Post by: Kp on December 26, 2004, 10:49 PM
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:

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] == '.');
}
Title: Re: Function similar to strstr
Post by: Eibro on December 26, 2004, 10:53 PM
Even better would be to check for ispunct && isspace.
Title: Re: Function similar to strstr
Post by: Adron on December 27, 2004, 02:15 AM
But he wants to treat different characters separately... Aren't [()! punctuation?