Question 3 [15 Marks) Write a C++ code to read a line of string as an input and do the following operations. Do proper input o validation to your input. 1) Capitalize first and last character of each word in the given string. [3 Marks] ii) Delete a word from the given string. Popup a message if the string is empty. [5 Marks) Page 3 of 6 iii) Add a word in the middle of the given string. Capitalize the new word if it already exists. [5 Marks] For proper input validation [2 marks]
#include<iostream>
using namespace std;
string FirstAndLast(string str)
{
string ch = str;
for (int i = 0; i < ch.length(); i++)
{
int k = i;
while (i < ch.length() && ch[i] != ' ')
i++;
ch[k] = (char)(ch[k] >= 'a' && ch[k] <= 'z'
? ((int)ch[k] - 32)
: (int)ch[k]);
ch[i - 1] = (char)(ch[i - 1] >= 'a' && ch[i - 1] <= 'z'
? ((int)ch[i - 1] - 32)
: (int)ch[i - 1]);
}
return ch;
}
void empty(string s){
if(s==" "){
cout<<"The string is empty\n";
}
}
string removeWord(string str, string word)
{
if (str.find(word) != string::npos)
{
size_t p = -1;
string tempWord = word + " ";
while ((p = str.find(word)) != string::npos)
str.replace(p, tempWord.length(), "");
tempWord = " " + word;
while ((p = str.find(word)) != string::npos)
str.replace(p, tempWord.length(), "");
}
return str;
}
int main()
{
cout<<"Enter a string: \n";
string na;
getline(cin,na);
cout<<FirstAndLast(na)<<endl;
}
Comments
Leave a comment