w3resource

C++ String Exercises: Reverse the words in a string that have odd lengths

C++ String: Exercise-35 with Solution

Write a C++ program to reverse all words that have odd lengths in a string.

Test Data:
("Exercises Practice Solution" ) -> "sesicrexE Practice Solution"
("The quick brown fox jumps over the lazy dog") -> "ehT kciuq nworb xof spmuj over eht lazy dog."

Sample Solution:

C++ Code:

#include <bits/stdc++.h>

using namespace std;

std::string test(std::string s) {
	std::stringstream str(s);
	std::string temp, result("");
	while(std::getline(str, temp, ' ')){
		if((temp.length()&1)==1)std::reverse(temp.begin(),temp.end());
		result+=temp+" ";
	}
	result.pop_back();
	return result;
}

int main()
{
	string text = "Exercises Practice Solution";
	cout << "String: " << text;
	cout << "\nReverse the words in the said string that have odd lengths:\n";
	cout << test(text) << endl;	 
	text = "The quick brown fox jumps over the lazy dog.";
	cout << "\nString: " << text;
	cout << "\nReverse the words in the said string that have odd lengths:\n";
	cout << test(text) << endl;	
}

Sample Output:

String: Exercises Practice Solution
Reverse the words in the said string that have odd lengths:
sesicrexE Practice Solution

String: The quick brown fox jumps over the lazy dog.
Reverse the words in the said string that have odd lengths:
ehT kciuq nworb xof spmuj over eht lazy dog.

Flowchart:

Flowchart: Reverse the words in a string that have odd lengths.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous C++ Exercise: Remove a word from a given string.

Next C++ Exercise: Check two consecutive, identical letters in a word.

What is the difficulty level of this exercise?



Share this Tutorial / Exercise on : Facebook and Twitter

C++ Programming: Tips of the Day

How to replace all occurrences of a character in string?

std::string doesn't contain such function but you could use stand-alone replace function from algorithm header.

#include <algorithm>
#include <string>

void some_func() {
  std::string s = "example string";
  std::replace( s.begin(), s.end(), 'x', 'y'); // replace all 'x' to 'y'
}

Ref: https://bit.ly/3niU71x