Search This Blog

C program to Find Index of a Substring in a String

Here, we will see a function written in C language, which helps to find the index (starting index) of any substring in a given string. The function returns the index of first letter of the first occurrence substring inside the original string. The function in C language is as follows:


int indexof(char *subString,int fromIndex,char *MainString)
{
 int Mainlength,subLength,i,j,retIndex=-1;
 Mainlength=strlen(MainString);
 subLength=strlen(subString);
 if(Mainlength<1||subLength<1||Mainlength-fromIndex<subLength)
  return(-1);
 for(i=fromIndex;Mainlength-i>=subLength;i++)
  {
  if(*(MainString+i)==*(subString))
   {
   retIndex=i;
   for(j=0;j<subLength;j++)
    {
    if(*(MainString+i+j)!=*(subString+j))
     {
     retIndex=-1;
     break;
     }
    }
   if(retIndex!=-1)
    return retIndex;
   }
  }
 return (-1);
}

The function returns -1, if the substring cannot be found within the main string.

No comments: