Find whether the given sub-string present in the string, If so, print the index else '-1' (using library function)
For Example:
If the given string is "coderegister" and the sub-string to search is "reg"
Output should be "4", which is the index of the first occurrence of the sub-string in the main string
Implementation:
For Example:
If the given string is "coderegister" and the sub-string to search is "reg"
Output should be "4", which is the index of the first occurrence of the sub-string in the main string
Implementation:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
/* Character pointers to hold the starting address of 1-D character array of size 256 characters */
char *m,*s;
/* constant character pointer to hold the address of the first match of the sub-string
in the main string */
const char *p;
/* allocate the memory block of 256 characters to store the main string */
m=(char*)malloc(sizeof(char)*256);
/* allocate the memory block of 256 characters to store the sub-string */
s=(char*)malloc(sizeof(char)*256);
/* Get the main string from the user */
scanf("%s",m);
/* Get the sub-string from the user */
scanf("%s",s);
/* strstr() library function will find a sub-string match in the main string
If there is a match, it will store the address of the first occurence of the match
Else, it will store NULL in the constant character pointer */
p=strstr(m,s);
/* So, if the sub-string is not found in the given main string, NULL is stored
in the pointer */
if(p==NULL)
printf("-1");
/* Else, to print the index, subtract the sub-string match address and starting address
of the main string*/
else
printf("%d",(p-m));
return 0;
}