Finding indexes where substring is present

Viewed 39

So right now my code checks if the sub string is present in the code and returns true or false, I would like to find where these substrings are located in the total string. how can you implement that.

#include <stdio.h>
#include <stdbool.h>

bool checksub(const char *strng,const char *subs){
  if (*strng=='\0' && *subs!='\0'){
    return false;
  }
  if (*subs=='\0'){
    return true;}
  if (*strng==*subs){
    return checksub(strng+1,subs+1);
  }
  return false;
}
bool lsub(char *strng,char *subs){
  if (*strng=='\0'){
    return false;
  }
  if (*strng==*subs){
    if (checksub(strng,subs)){
      return 1;
    }
  }
  return lsub(strng+1,subs);
}

int main(){
  
  printf("%d\n",checksub("ababuu","ab"));
  printf("%d\n",checksub("the bed bug bites","bit"));
  return 0;
}
1 Answers

First you should get rid of recursion since it's often slow and dangerous, for nothing gained.

A (naive) version of strstr that returns an index rather than a pointer might look like this:

int strstr_index (const char* original, const char* sub)
{
  int index = -1;

  for(const char* str=original; *str!='\0' && index==-1; str++)
  {
    for(size_t i=0; str[i]==sub[i] && str[i]!='\0'; i++)
    {
      if(sub[i+1] == '\0')
      {
        index = (int)(str - original);
        break;
      }
    }
  }

  return index;
}

This returns -1 if not found, otherwise an index.

  • It iterates across the string one character at a time.
  • When a character match with the sub string is found, it starts executing the inner loop as well.
  • If the inner loop continues to find matches all the way to the end of the sub string, then we found a match.
  • The index can be obtained by pointer arithmetic: the start address of the found sub string minus the start of the string. The result of that subtraction is strictly speaking a special integer type called ptrdiff_t, but I used int to simplify the example.
Related