-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathword_reversal_tool.cpp
75 lines (56 loc) · 1.25 KB
/
word_reversal_tool.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
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
63
64
65
66
67
68
69
70
71
72
73
74
75
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function used to reverse a string
// from index l to r
void reversed(string& s, int l, int r)
{
while (l < r) {
// Swap characters at l and r
swap(s[l], s[r]);
l++;
r--;
}
}
// Function to reverse the given string
string reverseString(string str)
{
// Add space at the end so that the
// last word is also reversed
str.insert(str.end(), ' ');
int n = str.length();
int j = 0;
// Find spaces and reverse all words
// before that
for (int i = 0; i < n; i++) {
// If a space is encountered
if (str[i] == ' ') {
// Function call to our custom
// reverse function()
reversed(str, j, i - 1);
// Update the starting index
// for next word to reverse
j = i + 1;
}
}
// Remove spaces from the end of the
// word that we appended
str.pop_back();
// Reverse the whole string
reversed(str, 0, str.length() - 1);
// Return the reversed string
return str;
}
// Driver code
int main()
{
// string str = "I like myself";
string sentence;
cout << "Type the sentence you want to reverse: ";
getline (cin, sentence);
// Function call
string rev = reverseString(sentence);
// Print the reversed string
cout << rev;
return 0;
}