A. Write program in C++ (Check substrings, const reference parameters, loop, cha
ID: 3686580 • Letter: A
Question
A. Write program in C++
(Check substrings, const reference parameters, loop, char array processing)
Write the following function to check whether string s1 is a substring 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
Enter the second string: We welcome you!
indexOf("welcome", "We welcome you!") is 3"
"Enter the first string: welcome
"Enter the second string: We invite you!
indexOf("Welcome", "We welcome you!") is -1
Explanation / Answer
// C++ program for Naive Pattern Searching algorithm
#include<iostream>
#include<cstring>
using namespace std;
int indexOf(const string& s1, const string& s2)
{
int M = s1.size();
int N = s2.size();
/* A loop to slide pat[] one by one */
for (int i = 0; i <= N - M; i++)
{
int j;
/* For current index i, check for pattern match */
for (j = 0; j < M; j++)
if (s1[i+j] != s2[j])
break;
if (j == M) { // if pat[0...M-1] = txt[i, i+1, ...i+M-1]
return i;
}
}
}
/* Driver program to test above function */
int main()
{
string s1 = "welcome";
string s2 = "We welcome you!";
cout<<"Sunstring found at index "<<indexOf(s1, s2)<<endl;;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.