How to reverse the letters of all the words only, not of the full string?

I want to reverse the letters of all the words only, not the full string.
For example:
Input: You are Mike.
Output: uoY era .ekiM

How to do this using the functions of string class?

I started with a approach in which I tried to find the space using str.find(' ') and reverse the letters before the space position. But I could do this for the first word only.

How to do it?
Last edited on
Do you need to preserve the whitespace verbatim?

If not, then read and print one word at a time.
using stringstream,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <sstream>
using namespace std;

string rev (string s)
{
	char temp;
	unsigned long long int i=0, lli = s.length()-1;
	while(i<lli)
		{ 
			temp = s[i]; 
			s[i] = s[lli]; 
			s[lli] =temp; 
			i++;
			lli--;
		}	
return s;
}

int main()
{
	string st = "you are  Mike.";
	stringstream ss;
	string s1;
	ss << st;
	while(ss>>s1)
	{
		s1 = rev(s1);
		cout << s1 << " ";
	}

return 0;
}


EDIT: notice that multiple spaces are converted into single space.
Last edited on
Topic archived. No new replies allowed.