**6.43 (Check substrings) Write the following function to check whether string s
ID: 3598827 • Letter: #
Question
**6.43 (Check substrings) Write the following function to check whether string sl is a substring of string s2. The function returns the first index in s2 if there is a match. Otherwise, return -1 int indexOf(const string& s1, const string& s2) Write a test program that reads two strings and checks whether the first string is a substring of the second string. Here is a sample run of the program: Enter the first string: welcome tr Enter the second string: We welcome you!Ente indexOf("welcome", "We welcome you!") is 3 Enter the first string: welcome -Enter Enter the second string: We invite you! Enter indexof("welcome", "We invite you!") is -1Explanation / Answer
#include <iostream>
#include <string>
using namespace std;
int indexOf(string &firstString, string &secondString){
if(secondString.size() > firstString.size())
return -1;
for (int i = 0; i < firstString.size(); i++){
int j = 0;
int k = i;
while (firstString[k] == secondString[j] && j < secondString.size()){
j++;
k++;
}
if (j == secondString.size())
return i;
}
return -1;
}
int main(){
string firstString, secondString;
cout << "Enter first string:";
getline(cin, firstString);
cout << "Enter second string:";
getline(cin, secondString);
cout<<"indexOf(""<<firstString<<"", ""<<secondString<<"") is "<<indexOf(firstString, secondString)<<endl;
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.