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 new 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?
C++ Programming: Tips of the Day
What is the usefulness of `enable_shared_from_this?
It enables you to get a valid shared_ptr instance to this, when all you have is this. Without it, you would have no way of getting a shared_ptr to this, unless you already had one as a member.
class Y: public enable_shared_from_this{ public: shared_ptr f() { return shared_from_this(); } } int main() { shared_ptr p(new Y); shared_ptr q = p->f(); assert(p == q); assert(!(p < q || q < p)); // p and q must share ownership }
The method f() returns a valid shared_ptr, even though it had no member instance. Note that you cannot simply do this:
class Y: public enable_shared_from_this{ public: shared_ptr f() { return shared_ptr (this); } }
The shared pointer that this returned will have a different reference count from the "proper" one, and one of them will end up losing and holding a dangling reference when the object is deleted.
Ref : https://bit.ly/3pwVzzz
- Weekly Trends
- 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
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises