-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathReverseWordsOfSentence.cpp
77 lines (53 loc) · 1.18 KB
/
ReverseWordsOfSentence.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
76
77
#include<iostream>
#include<stack>
#include<algorithm>
#include<cstring>
using namespace std;
//program to reverse Words of a sentence
void ReverseWords(string &s)
{
int start = 0;
int i = 0;
//to remove spaces in the starting
while( s[i] == ' ') s.erase(i, 1);
reverse(s.begin(), s.end());
int size = s.size();
for(i = 0; i < size - 1; i++){
//removing empty spaces
if( s[i] == ' '){
if( i == start ){
s.erase(i--,1);
size--;
}
else{
reverse(s.begin()+start, s.begin()+i);
start = i+1;
}
}
}
reverse(s.begin() + start, s.end());
cout<<s;
}
//function to count words
int countWords(string s)
{
int count = 0 ;
int word = 0;
int i = 0 ;
int size = s.size()-1;
while(i <= size)
{
if(s[i] == ' ') word = 0;
else if(++word==1)
count++;
i++;
}
return count;
}
int main()
{
string s = " hey how are you";
ReverseWords(s);
cout<<endl<<countWords(s);
return 0;
}