word occurrence in string using pointer

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

int count (const char *str, const char *search);

int count (const char *str, const char *search)
{
    int counter = 0,flag = 0;
    const char *holdstr, *holdsearch;
    do
    {
        for (holdstr = str, holdsearch = search ;
             *holdsearch != '\0' && *holdstr == *holdsearch ;
             holdsearch++,holdstr++) {}

            if ( *holdsearch == '\0' )
            {
                counter++;
                flag = 1;
            }

    }while (*(str++));

    if (flag) return counter;
    return -1;
}

int main()
{
    const char *find = "the";
    const char *arr1 = "the cat sat on the mat";
    const char *arr2 = "theqqqqq cat sat on the mat";
    const char *arr3 = "-qthe-- cat sat on theok mat";

    int val = count(arr1, find);
    printf("%d\n", val);
    val = count(arr2, find);
    printf("%d\n", val);
    val = count(arr3, find);
    printf("%d\n", val);

    return 0;
}

I try to find one-to-one correspondence words. But, I get also some other words which are included the specified word. The function is similar to strstr(). I have also realized that it goes for strstr() How can be the issue fixed?

Output                  Expected Output
-------                 ---------------
2                       2
2                       1
2                       0

Upvotes: 0

Views: 1383

Answers (1)

BLUEPIXY
BLUEPIXY

Reputation: 40145

sample of idea of fix

int count (const char *str, const char *search)
{
    int counter = 0;
    const char *holdstr, *holdsearch, *wordtop, *s=str;
    do
    {
        for (wordtop = holdstr = s, holdsearch = search ;
             *holdsearch != '\0' && *holdstr == *holdsearch ;
             holdsearch++,holdstr++)
             ;
        //                   top               space                     end          space
        if (!*holdsearch && (wordtop == str || isspace(wordtop[-1])) && (!*holdstr || isspace(*holdstr)))
        {
            counter++;
        }

    }while (*s++);

    return counter;//no needs flag if return 0;
}

Upvotes: 1

Related Questions