-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathReverseSentence.cpp
More file actions
62 lines (49 loc) · 878 Bytes
/
Copy pathReverseSentence.cpp
File metadata and controls
62 lines (49 loc) · 878 Bytes
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
Reverse Sentence
Sample Input:
Hello World
Sample Output:
World Hello
*/
#include <iostream>
#include <string>
using namespace std;
void swap(char & a, char & b)
{
a = a ^ b;
b = a ^ b;
a = a ^ b;
}
void reverseString(string & s, int b, int e)
{
while (b < e) {
swap(s[b ++], s[e --]);
}
}
void reverseSentence(string & s)
{
reverseString(s, 0, s.length() - 1);
cout << s << endl;
int head = 0, tail = 0;
while (head < s.length()) {
while (head < s.length() && s[head] == ' ') {
head ++;
}
if (head >= s.length()) return;
tail = head;
while (tail < s.length() && s[tail] != ' ') {
tail ++;
}
reverseString(s, head, tail - 1);
head = tail + 1;
}
}
int main()
{
string s = "";
while (getline(cin, s)) {
reverseSentence(s);
cout << s << endl;
}
return 0;
}