Answer to Question #284855 in C++ for ihle

Question #284855

Write a C++ code to read a line of string as an input and do the following operations. Do proper input validation to your input.

i) 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]

iii) Add a word in the middle of the given string. Capitalize the new word if it already exists.

iv) For proper input validation


1
Expert's answer
2022-01-04T16:21:37-0500
#include <iostream>
#include <string>

std::string Capitalize(std::string str)
{

    std::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;
}
int main ()
{
    std::string input_string;
    getline(std::cin, input_string);
    input_string = Capitalize(input_string);
    if(input_string.empty())
    {
        std::cout<<"String is empty"<<std::endl;
    }
    std::string word_to_remove;
    getline(std::cin, word_to_remove);
    unsigned long length = word_to_remove.size();
    if (length != std::string::npos)
    {
        input_string.erase(length, word_to_remove.length());
    }
    std::string word_to_insert = "hello";
    input_string.insert(4, word_to_insert);
    std::cout<<input_string<<std::endl;
    input_string = Capitalize(input_string);
    
    
    
    std::cout<<input_string<<std::endl;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog