In C find position of substring in a string

Mugambo picture Mugambo · Aug 6, 2012 · Viewed 72.5k times · Source

Here is a program to accept a:

  1. Sentence from a user.
  2. Word from a user.

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;
}

Answer

Gingi picture Gingi · Aug 7, 2012

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;