• Welcome to Valhalla Legends Archive.
 

Function similar to strstr

Started by Mephisto, December 26, 2004, 07:09 PM

Previous topic - Next topic

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.

Kp

// 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)] == ' ';
}
[19:20:23] (BotNet) <[vL]Kp> Any idiot can make a bot with CSB, and many do!

Mephisto

#2
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)] == '.';
}

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:

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] == '.');
}
[19:20:23] (BotNet) <[vL]Kp> Any idiot can make a bot with CSB, and many do!

Eibro

Even better would be to check for ispunct && isspace.
Eibro of Yeti Lovers.

Adron

But he wants to treat different characters separately... Aren't [()! punctuation?