How to find a word in string not a substring

Viewed 645

Is there any function for finding an exact word in string?

char *str = "My birthday is 32.32.2133";
char *new = strstr(str, "day");

So, in (new) i got a pointer on 'd' symbol in (str). But I need a pointer not to a substring, but to a word in a string. So in this case i need a NULL pointer here. Is there any function for finding an exact word in string?

So, if I have

char *str = "My birthday is 32.32.2133";
char *new = func(str, "birthday");

new will point on a b symbol,

if I have

char *str = "My birthday is 32.32.2133";
char *new = func(str, "day");

new will point on a NULL

3 Answers

Is there any function for finding an exact word in string?

No, there is no function doing that.

You'll have to write your own code. That can be done in many different ways. Here is one approach (with some pseudo code).

1: Use strstr to see in the word you search is at all present.

pm = strstr(str, word);
if (pm == NULL) return NULL;

If present:

2: Check that your search word is in fact starting a new word in the string. This means that either there must be a space just before the location returned by strstr or the location returned by strstr must be identical to the start of the string.

if (pm == str) ....  // Fine, start of string

else if (*(pm-1) == ' ') ...  // Fine, space just before the word

else ...  // Bad, not a complete word

3: Check that your search word is in fact ending a word in the string. This means that either there must be a space just after the location returned by strstr plus the size of your search word or the location returned by strstr plus the size of your search word must be identical to the end of the string.

if (*(pm + strlen(word)) == '\0') ....  // Fine, end of string

else if (*(pm + strlen(word)) == ' ') ...  // Fine, space just after the word

else ...  // Bad, not a complete word

In order to determine if the word you are searching for within a string exists as a whole word and not part of a substring of another word within the string, you simply need to located the substring (whether a whole word or not) and then check if the character before and after is [A-Za-z0-9] (e.g. isalnum() -- adjust the test as needed).

If the character before or after your substring is an alpha-character or digit, then your search word does not exist as a whole-word within the string.

If, on the other had, you find the character that comes before (if any) your substring, and the character that comes after (if any) your substring is whitespace of punctuation -- then you can consider the word a whole word within the string.

You can do that by simply checking the length of your search term, locating your search substring within the string and then using pointer arithmetic (or array indexing) to isolate the character before and after your substring (making sure you test whether you search word begins at the beginning or end of your string as well).

A simple function could be:

const char *findword (const char *s, const char *w)
{
    size_t len = strlen (w);                /* get length of word */
    char *sp = strstr (s, w);               /* get start-pointer to word in string */
    
    if (!sp)                                /* if start-pointer NULL - not found */
        return NULL;
    
    if (sp > s && isalnum (*(sp-1)))        /* if not 1st char and char before sp */
        return NULL;                        /* is [A-Za-z0-9], not a whole word */
    
    if (sp[len] && isalnum(sp[len]))        /* if end not nul-terminating char, and */
        return NULL;                        /* and char after w is [A-Za-z0-9], not
                                               a whole word */
    
    return sp;                              /* return pointer to whole word */
}

(note: if you attempt to use strtok() or strsep() both modify the search string, so you must ensure it is mutable)

The function returns a pointer to the beginning of the whole word match within your string on success, NULL otherwise. You can adjust the search to limit what characters are considered valid at each end of the word.

A short program using the function and taking the sentence to search as the first argument and the word to search for as the second (or using "my cat likes hotdogs" and "dog" for defaults if no, or only the sentence is given), you could do:

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

const char *findword (const char *s, const char *w)
{
    size_t len = strlen (w);                /* get length of word */
    char *sp = strstr (s, w);               /* get start-pointer to word in string */
    
    if (!sp)                                /* if start-pointer NULL - not found */
        return NULL;
    
    if (sp > s && isalnum (*(sp-1)))        /* if not 1st char and char before sp */
        return NULL;                        /* is [A-Za-z0-9], not a whole word */
    
    if (sp[len] && isalnum(sp[len]))        /* if end not nul-terminating char, and */
        return NULL;                        /* and char after w is [A-Za-z0-9], not
                                               a whole word */
    
    return sp;                              /* return pointer to whole word */
}

int main (int argc, char **argv) {
    
    char *text = argc > 1 ? argv[1] : "my cat likes hotdogs",
         *word = argc > 2 ? argv[2] : "dog";
        
    printf ("text : %s\nword : %s\n%s\n",
            text, word, findword (text, word) ? "FOUND" : "NOT FOUND");
}

(the program above just uses the return to determine whether to output "FOUND" on successfully finding word as a whole-word within the string, or "NOT FOUND" on failure)

Example Use/Output

Default case looking for "dog" as whole word:

$ ./bin/findwholeword
text : my cat likes hotdogs
word : dog
NOT FOUND

Looking for whole word "cat":

$ ./bin/findwholeword "my cat likes hotdogs" "cat"
text : my cat likes hotdogs
word : cat
FOUND

Looking for whole word "like":

$ ./bin/findwholeword "my cat likes hotdogs" "like"
text : my cat likes hotdogs
word : like
NOT FOUND

Looking for whole word "likes":

$ ./bin/findwholeword "my cat likes hotdogs" "likes"
text : my cat likes hotdogs
word : likes
FOUND

Let me know if you have any further questions.

Here is the solution how to find a word in a string. Details are added as comments into the code below:

#include <stdio.h>
#include <string.h>
  
int main()
{
    char s[1000],w[1000];  
    int n,a[1000],i,j,k=0,l,found=0,t=0;
 
    printf("Enter  the string : ");
    scanf ("%[^\n]%*c", s);
    printf("Enter word to be searched: ");
    scanf ("%[^\n]%*c", w);
    
    // Checking how many words are there in the given string and store those lengths of words in an array
    for(i=0;s[i];i++)
    {
        if(s[i]==' ')
        {
            a[k++]=i;
        }
    }
    
    a[k++]=i;
    
    j=0;
    
    for(i=0;i<k;i++)
    {
        n=a[i]-j; // Finding word length from the number of words in the given string
        
        if(n==strlen(w)) // Checking whether the length of a stored word is equal to the length of the searched word or not, if then check all the characters
        {
            t=0;
            
            for(l=0;w[l];l++)
            {
                if(s[l+j]==w[l])
                {
                    t++;
                }
            }
            
            if(t==strlen(w))
            {
                found++;
                printf("word '%s'  is occurred at location=%d \n",w,j);
 
            }
        }
    
        j=a[i]+1; // Update the length of previous stored word
    }
    
    if(found==0)
    {
        printf("Word '%s' is not available in the given string.", w);
    }

    return 0;
}
Related