Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match exact string with strstr

Suppose I have the following string:

in the interior of the inside is an inner inn

and I want to search, say, for the occurences of "in" (how often "in" appears).

In my program, I've used strstr to do so, but it returns false positives. It will return:

- in the interior of the inside is an inner inn
- interior of the inside is an inner inn
- inside is an inner inn
- inner inn
- inn

Thus thinking "in" appears 5 times, which is obviously not true.

How should I proceed in order to search exclusively for the word "in"?

like image 722
Alexandru Dinu Avatar asked Jun 14 '26 11:06

Alexandru Dinu


1 Answers

Try the following

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main(void) 
{
    char *s = "in the interior of the inside is an inner inn";
    char *t = "in";
    size_t n = strlen( t );

    size_t count = 0;
    char *p = s;

    while ( ( p = strstr( p, t ) ) != NULL )
    {
        char *q = p + n;
        if ( p == s || isblank( ( unsigned char ) *( p - 1 ) ) )
        {
            if ( *q == '\0' || isblank( ( unsigned char ) *q ) ) ++count;
        }
        p = q;
    }

    printf( "There are %zu string \"%s\"\n", count, t );

    return 0;
}

The output is

There are 1 string "in"

You can also add a check for ispunct if the source string can contain puctuations.

like image 121
Vlad from Moscow Avatar answered Jun 16 '26 06:06

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!