/
9stringProblem.cpp
60 lines (55 loc) · 1.1 KB
/
9stringProblem.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
#include <iostream>
#include <vector>
#include <string>
using namespace std;
/*Q9- Given a string s, reverse the order of characters in each word within a sentence while
still preserving the whitespaces and initial word order.
*/
vector <int> whitespaceIndex(string s)
{
vector <int> index = {0};
for(int i = 0; i < s.size()-1; i++)
{
if(s[i] == ' ')
{
index.push_back(i-1);
index.push_back(i+1);
continue;
}
else{continue;}
}
index.push_back(s.size()-1);
return index;
}
string reverse(string s, int x, int y)
{
string result = "";
for(int i = y; i >= x; i--)
{
result.push_back(s[i]);
}
return result;
}
string answer(string s)
{
string result = "";
vector <int> index = whitespaceIndex(s);
for(int i = 0; i < index.size(); i += 2)
{
string x = reverse(s,index[i],index[i+1]);
for(int j = 0; j < x.size(); j++)
{
result.push_back(x[j]);
}
result.push_back(' ');
}
return result;
}
int main()
{
string s ;
cout<< "give the string : ";
getline(cin,s);
cout<< answer(s);
cout<< endl;
}