string revers

write a code to reverse words of a string. please do it in the simplest way it will help to understand.......
closed account (SECMoG1T)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
std::string reverse_string(std::string s)
{
    int start=0, stop=s.size()-1;
  
   while(start<=stop)
    {
        char temp=s[start];
        s[start]=s[stop];
        s[stop]=temp;
        ++start; --stop;
    }

  return s;
}
    


i guess that would help.
Last edited on
Note that the code posted by Andy also reverses the order of the words in the string.
closed account (SECMoG1T)
@peter i agree, @Sazzad sorry i din't take my time to think about the question, about reversing the words in a string is a different thing from what i gave , i'll edit my post to take care of words.
This is probably homework so it might be better if you don't give him the complete solution.
dear it is not a assignment or home work.if it was thn i will try it by myself :)
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
// reverse order of words in string.
#include <iostream>
#include <string>
using namespace std;

int main (){
	
	string s = "these words will be     reversed";
	string rev = "";
	int k = s.size()-1;
	
	for(int i=k; i>=0; i--){
		if(s[i] == ' '){
			for(int j=i+1; j<=k; j++){
				rev += s[j];							
			}
			k=i-1;
			rev += ' ';
		}		
	}
	
	for(int i=0; i<=k; i++){
		rev += s[i];
	}
	
	cout << rev << endl;
	
return 0;
}
Topic archived. No new replies allowed.