Here is a program to accept a:
How do I find the position of the word entered in the sentence?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    char sntnc[50], word[50], *ptr[50];
    int pos;
    puts("\nEnter a sentence");
    gets(sntnc);
    fflush(stdin);
    puts("\nEnter a word");
    gets(word);
    fflush(stdin);
    ptr=strstr(sntnc,word);
    //how do I find out at what position the word occurs in the sentence?
    //Following is the required output
    printf("The word starts at position #%d", pos);
    return 0;
}
                The ptr pointer will point to the beginning of word, so you can just subtract the location of the sentence pointer, sntnc, from it:
pos = ptr - sntnc;
                        Just for reference:
char saux[] = "this is a string, try to search_this here";
int dlenstr = strlen(saux);
if (dlenstr > 0)
{
    char *pfound = strstr(saux, "search_this"); //pointer to the first character found 's' in the string saux
    if (pfound != NULL)
    {
        int dposfound = int (pfound - saux); //saux is already pointing to the first string character 't'.
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With