C++ String Exercises: Reverse the words of three or more lengths in a string
C++ String: Exercise-32 with Solution
Write a C++ program that takes a string and reverses the words of three or more lengths in a string. Return the updated string. As input characters, only spaces and letters are permitted.
Sample Data:
("The quick brown fox jumps over the lazy dog") -> “ehT kciuq nworb xof spmuj revo eht yzal god”
("Reverse the words of three or more") -> “esreveR eht sdrow of eerht or erom”
("ABcDef") -> “feDcBA”
Sample Solution:
C++ Code:
#include <bits/stdc++.h>
using namespace std;
std::string test(std::string text) {
int i = 0;
int l = text.size();
while (i < l) {
size_t j = text.find(' ', i);
if (j == text.npos) j = l;
if (i + 3 <= j) std::reverse(&text[i], &text[j]);
i = j + 1;
}
return text;
}
int main() {
string text = "The quick brown fox jumps over the lazy dog";
//string text ="ABcDef";
//string text = "Reverse the words of three or more";
cout << "Original string: " << text;
cout << "\n\nReverse the words of three or more lengths of the said string:\n";
cout << test(text) << endl;
}
Sample Output:
Original string: The quick brown fox jumps over the lazy dog Reverse the words of three or more lengths of the said string: ehT kciuq nworb xof spmuj revo eht yzal god
Flowchart:

C++ Code Editor:
Contribute your code and comments through Disqus.
Previous C++ Exercise: Check whether a string is uppercase or lowercase.
Next C++ Exercise: Check first string contains letters from the second.What is the difficulty level of this exercise?
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join