In: Computer Science
Write a function to check whether string s1 is a substring of string s2. The function returns the first index in s2 if there is a match. Otherwise, return -1. For example, the function should return 2 if s1 is "to" and s2 is "October". If s1 is "andy" and s2 is "candy", then the function should return 1. The function prototype is as follows: int indexOf(const char *s1, const char *s2).
Here is your c++ code for above problem. I have successfully executed this code using TurboC++ compiler.Header file inclusion statements may be different with different compiler.You can easily adjust it according to your compiler.
#include<iostream.h>
#include<stdio.h>
int indexOf(const char *s1, const char *s2) //Function
definition
{
int m,n;
for(m=0;*(s1+m)!='\0';m++); //finding length of string s1
for(n=0;*(s2+n)!='\0';n++); //finding length of string s2
for (int i = 0; i <= n - m; i++) {
int j;
for (j = 0; j < m; j++) //loop to check entire
substring in given string
if (s2[i + j] != s1[j])
break;
if (j == m)
return i;
}
return -1;
}
int main()
{
char s1[10];
char s2[100];
cout<<"Enter the substring to be search:";
gets(s1); //getting substring from user
cout<<"Enter the string:";
gets(s2); //getting string from user
int res = indexOf(s1, s2);
if (res == -1)
cout << "Not present";
else
cout << "Present at index " << res;
return 0;
}
Here is your output: