Write a computer program which given two C-strings as input, checks if the first
ID: 3676389 • Letter: W
Question
Write a computer program which given two C-strings as input, checks if the first is a substring of the second. You are supposed to allow whitespaces in the input strings. You program should interpret a new line as the end of first input string and similarly for the second input string. Note that if s_1(0...l_2,- 1] and s_2[0... l_2 - 1] are character strings of lengths l_1, and l_2 respectively, we say that is a substring of s_2 if there exists an integer i, 0 less than or equal to i less than or equal to l_2 -(l_1 - 1), such that s_1[j] = s_2[i + j] for j = 0,..., l_1 - 1 For example, "obl" is a substring of "Problem 2", but "oblm" is not a substring of "Problem 2". Your program is supposed to give a YES/NO answer only.Explanation / Answer
This below c++ program will work as per given program statement.
i.e wither string contains the sub string or not.
if sub string is found will print true else false.
Checked manually instead of string functions.
Code :
#include<iostream>
using namespace std;
int main()
{
string st1, subst1, message=" ";
bool found=false;
cout<<"Enter string :"<<endl;
cin>>st1;
cout<<"Enter Sub String "<<endl;
cin>>subst1;
for (int a=0; !found && a<st1.length();a++)
{
if (st1[a]==subst1[0])
{
found = true; // there's some hope
for (int k=0; found && k<subst1.length(); k++)
{
if (a+k>=st1.length() || st1[a+k]!=subst1[k]) // oops! might overflow or fail
found = false; // this will also end the inner loop
}
}
}
message = found ? "True":"False";
cout<< message<<endl;
return 1;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.