Answer to Question #178963 in C++ for Luna

Question #178963

Write a program that reads in a line of text and replaces all four-letter words with the word “love”.  For example:

the input string:

I hate you, you dodo !

Should produce the output:

I love you, you love!


Of course, the output will not always make sense.


For example, the input string:

John will run home.

Should produce the output:

Love love run love.


If the four-letter word starts with a capital letter, it should be replaced by “Love”, not by “love”. You need not check capitalization, except for the first letter of a word. A word is any string consisting of the letters of the alphabet and delimited at each end by a blank, the end of a line, or any other character that is not a letter. Your program should repeat this action until the user says to quit.



1
Expert's answer
2021-04-07T00:19:21-0400
#include <iostream>
#include <string>
#include <cctype>
using namespace std;


int main()
{
    string str;
     
    while (true) {
        cout << "Enter a strings (type \'quit\' to exit)" << endl;
        getline(cin, str);
        if (str == "quit")
            break;

        int b = 0;
        int n = str.length();
        while (b < n) {
            while (b < n && !isalpha(str[b]) ) 
                b++;
            int e = b+1;
            while (e < n && isalpha(str[e]))
                e++;
            if (e - b == 4) {
                if (isupper(str[b])) {
                    str.replace(b, 4, "Love");
                }
                else {
                    str.replace(b, 4, "love");
                }
            }
            b = e;
        }
        cout << "Output:" << endl;
        cout << str << endl << 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
APPROVED BY CLIENTS