-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstrmanip2.cpp
78 lines (65 loc) · 1.88 KB
/
strmanip2.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
78
// {"category": "String", "notes": "String with words in reverse order"}
#include <SDKDDKVer.h>
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <stack>
#include <Windows.h>
#include <strsafe.h>
using namespace std;
//------------------------------------------------------------------------------
//
// Given a string such as "The quick brown fox jumps over the lazy dog" write
// a function that returns the string with the words in reverse order
// "dog lazy the over jumps fox brown quick The".
//
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//
// Implementation
//
//------------------------------------------------------------------------------
void WordsInReverseOrder(char* pString, size_t cch)
{
if (nullptr == pString)
{
return;
}
size_t indexWord = 0;
stack<string> words;
string copy(pString);
string reversed;
for (size_t i = 0; i < strlen(pString) + 1; i++)
{
if (isspace(pString[i]) || '\0' == pString[i])
{
if (i > indexWord)
{
words.push(copy.substr(indexWord, i - indexWord));
}
indexWord = i + 1;
}
}
while (!words.empty())
{
if (!reversed.empty())
{
reversed += " ";
}
reversed += words.top();
words.pop();
}
StringCchCopyA(pString, cch, reversed.c_str());
}
//------------------------------------------------------------------------------
//
// Demo execution
//
//------------------------------------------------------------------------------
int _tmain(int argc, _TCHAR* argv[])
{
char string[] = "The quick brown fox jumps over the lazy dog";
WordsInReverseOrder(string, ARRAYSIZE(string));
cout << string << endl;
return 0;
}