-
Notifications
You must be signed in to change notification settings - Fork 7
/
155.cpp
47 lines (40 loc) · 844 Bytes
/
155.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
// C++ program to reverse a string
#include <bits/stdc++.h>
using namespace std;
// Function to reverse words*/
void reverseWords(string s)
{
// temporary vector to store all words
vector<string> tmp;
string str = "";
for (int i = 0; i < s.length(); i++)
{
// Check if we encounter space
// push word(str) to vector
// and make str NULL
if (s[i] == ' ')
{
tmp.push_back(str);
str = "";
}
// Else add character to
// str to form current word
else
str += s[i];
}
// Last word remaining,add it to vector
tmp.push_back(str);
// Now print from last to first in vector
int i;
for (i = tmp.size() - 1; i > 0; i--)
cout << tmp[i] << " ";
// Last word remaining,print it
cout << tmp[0] << endl;
}
// Driver Code
int main()
{
string s = "i like this program very much";
reverseWords(s);
return 0;
}