In C find position of substring in a string
Asked Answered
A

6

10

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;
}
Alphonsa answered 6/8, 2012 at 21:53 Comment(3)
you can subtract 2 pointers (to char) and interpret the result as an integer: position = ptr - sntnc;Scrophulariaceous
DON'T USE gets()! DON'T fflush() INPUT STREAMS!Scrophulariaceous
in Java / JavaScript we've exactly that function you need : indexOf. However a quick search enabled me to find a thread discussing what you need : a indexOf like function in C, please check out this post : https://mcmap.net/q/331631/-string-indexof-function-in-cChore
C
21

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;
Courtship answered 6/8, 2012 at 22:0 Comment(2)
...but only if ptr is not NULL.Moult
ptr is a char** pointer and sntnc is a char* pointer. How can we subtract them?Chalcopyrite
E
8

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'.
    }
}
Eugenol answered 17/4, 2013 at 14:36 Comment(0)
M
4

The return of strstr() is a pointer to the first occurence of your "word", so

pos=ptr-sntc;

This only works because sntc and ptr are pointers to the same string. To clarify when I say occurence it is the position of the first matching char when the matching string is found within your target string.

Mucoid answered 6/8, 2012 at 22:3 Comment(0)
M
3

You can use this simple strpos modification

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int strpos(char *haystack, char *needle, int offset);
int main()
{
    char *p = "Hello there all y'al, hope that you are all well";
    int pos = strpos(p, "all", 0);
    printf("First all at : %d\n", pos);
    pos = strpos(p, "all", 10);
    printf("Second all at : %d\n", pos);
}


int strpos(char *hay, char *needle, int offset)
{
   char haystack[strlen(hay)];
   strncpy(haystack, hay+offset, strlen(hay)-offset);
   char *p = strstr(haystack, needle);
   if (p)
      return p - haystack+offset;
   return -1;
}
Monahan answered 7/11, 2017 at 14:46 Comment(0)
G
2

For some reasons I was having trouble with strstr(), and I also wanted index.

I made this function to find the position of substring inside a bigger string (if exists) otherwise return -1.

 int isSubstring(char * haystack, char * needle) {
     int i = 0;
     int d = 0;
     if (strlen(haystack) >= strlen(needle)) {
         for (i = strlen(haystack) - strlen(needle); i >= 0; i--) {
             int found = 1; //assume we found (wanted to use boolean)
             for (d = 0; d < strlen(needle); d++) {
                 if (haystack[i + d] != needle[d]) {
                     found = 0; 
                     break;
                 }
             }
             if (found == 1) {
                 return i;
             }
         }
         return -1;
     } else {
         //fprintf(stdout, "haystack smaller\n"); 
     }
 } 
Gavrah answered 24/3, 2014 at 4:55 Comment(0)
A
0

My comment to the ORIGINAL post in this thread: This declaration is INCORRECT:

    char sntnc[50], word[50], *ptr[50];

C code would not even compile : it will fail on this line:

    ptr = strstr(sntnc,word);

So the line shall be changed to :

   char sntnc[50], word[50], *ptr;

And you do NOT need memeory allocated to 'ptr string'. You just need a pointer to char.

Abel answered 26/9, 2014 at 9:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.