-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReversewords.cpp
More file actions
55 lines (45 loc) · 1.24 KB
/
Reversewords.cpp
File metadata and controls
55 lines (45 loc) · 1.24 KB
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
#include<iostream>
#include<algorithm>
#include<vector>
#include <array>
#include<cmath>
#include <string>
#include <iostream>
#include <string>
using namespace std;
string reverseEachWord(const string& str) {
string result;
int start = 0;
// Iterate through the string character by character
while (start < str.length()) {
int end = start;
// Find the end of the current word
while (end < str.length() && str[end] != ' ') {
++end;
}
// Reverse the current word and add it to the result
for (int i = end - 1; i >= start; --i) {
result += str[i];
}
// Add the spaces after the word
while (end < str.length() && str[end] == ' ') {
result += ' ';
++end;
}
// Move to the next word
start = end;
}
return result;
}
int main()
{
cout << reverseEachWord("The quick brown fox jumps over the lazy dog");
return 0;
}
/*Description:
Complete the function that accepts a string parameter, and reverses each word in the string. All spaces in the string should be retained.
Examples
"This is an example!" ==> "sihT si na !elpmaxe"
"double spaces" ==> "elbuod secaps"
Strings
Fundamentals*/