- Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathreverseWordinString.cpp
33 lines (30 loc) · 804 Bytes
/
reverseWordinString.cpp
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>
usingnamespacestd;
voidreverse(string &s, int start, int end){
if(start>=end) return ;
swap(s[start],s[end]);
reverse(s,start+1,end-1);
}
string reverseWords(string s) {
int start = 0;
for(int i=0;i<s.length();i++){
if(s[i+1] == '' || s[i+1]=='\0'){
//Since s[i+1] is space or null character, s[i] is end of a word
int end = i;
reverse(s,start,end);
//Since s[i+1] is space or null character, s[i+2] may be the beginning of new word
start = i+2;
}
}
reverse(s,start,s.length()-1);
return s;
}
intmain()
{
string s,k;
cout << "Enter The String : ";
getline(cin, s);
k=reverseWords(s);
cout << s << endl;
cout << k << endl;
}