Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C find position of substring in a string

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;
}
like image 352
Mugambo Avatar asked Aug 06 '12 21:08

Mugambo


2 Answers

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;
like image 189
Gingi Avatar answered Oct 18 '22 18:10

Gingi


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'.
    }
}
like image 38
xtrm Avatar answered Oct 18 '22 19:10

xtrm