In: Computer Science
I need to write a C++ program that appends "not" into the string without using the append method or any standard libraries. It should return the string if there isn't an "is" in it.
Examples:
is is = is not is not
This is me = This is not me
What is yellow? = What is not yellow?
The sky is pink = The sky is not pink
isis = isis
What happened to you? = What happened to you?
C++ Code :
#include<iostream>
using namespace std;
// this method appends "not" into the string without
using the append method or any standard libraries.
// this method returns the string if there isn't an "is" in
it.
// this method accepts a parameter of user input string
string solve(string s)
{
string res = "";
// this is the resultant string
int n = (int)s.size();
// getting the size of the
input string
// if the size of the input string is 1, then directly
return it
if(n==1)
return s;
// if the size of the input string is 2, then check
whether it is "is" or not
else if(n==2)
{
// if the input string is "is",
then simply add "is not" to the resultant string and return
it
if(s[0]=='i' &&
s[1]=='s')
{
res += "is
not";
return
res;
}
// if the input string is not "is",
then simply return it directly
else
return s;
}
// if the size of the input string is greater than
2
else
{
for(int i=0;i<n;i++)
{
// this is for
first index of the input string
if(i==0)
{
// if the first word of the input string is
"is"
if(s[i]=='i' && s[i+1]=='s' &&
s[i+2]==' ')
{
res += "is not";
i++;
}
// else simply add the current character to the
resultant string
else
res += s[i];
}
// this is for
(n-2)th index of the input string
else
if(i==n-2)
{
// checking if the last word of the input string
is "is"
if(s[i-1]==' ' && s[i]=='i' &&
s[i+1]=='s')
{
res += "is not";
i++;
}
// else simply add the current character to the
resultant string
else
res += s[i];
}
// this is for
rest of the character of the input string
else
{
// if the current index word is "is", then
simply add "is not" to the resultant string
if(s[i-1] == ' ' && s[i]=='i' &&
s[i+1]=='s' && s[i+2]==' ')
{
res += "is not";
i+=2;
}
// else simply add the current character to the
resultant string
res += s[i];
}
}
// returning the resultant string
from this method
return res;
}
}
int main()
{
string s;
// this variable will take user input of
string
cout<<"Enter a string : ";
// asking
for the user input of string
getline(cin,s);
// taking
input from the user
string result = solve(s);
// calling
solve() for getting the resultant string or expected output and
storing to the result variable
cout<<"Resultant string is :
"<<result<<"\n";
// printing the resultant
string
}
Output :