-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreverse_sentense.cpp
85 lines (75 loc) · 1.56 KB
/
reverse_sentense.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
79
80
81
82
83
84
85
#include <iostream>
#include <vector>
#include <string>
#include <iterator>
#include <cassert>
using std::string;
char* last(char* s) {
while (*s != '\0') {
s++;
}
return --s;
}
void swap(char* a, char* b) {
char t = *a;
*a = *b;
*b = t;
}
void reverse_str(char* s) {
char* l = last(s);
while (std::distance(s, l) > 0) {
swap(s++, l--);
}
}
void reverse_str(char* s, char* p) {
while (std::distance(s, p) > 0) {
swap(s++, p--);
}
}
char* begin_word(char* s) {
while (*s == ' ' || *s == '\t' || *s == '\n') {
s++;
}
return s;
}
char* end_word(char* s) {
while (*s == ' ' || *s == '\t') {
s++;
}
while (*s != ' ' && *s != '\0' && *s != '\t' && *s != '\n') {
s++;
}
return --s;
}
void reverse_sentense(char* s) {
reverse_str(s);
while (*s != '\0') {
s = begin_word(s);
if (*s == '\0')
return;
char* w_e = end_word(s);
reverse_str(s, w_e);
s = ++w_e;
}
}
int main(int argc, char* arg[])
{
// std::cout << "hello, please enter your name..." << std::endl;
// string name;
// std::cin >> std::ws;
// std::getline(std::cin, name);
std::cout << "Hello, nice to meet you!" << std::endl;
while (1) {
std::cout << "hello, please enter you words..." << std::endl;
string line;
std::getline(std::cin, line, '\n');
std::cout << "you have enter:\n" << line << std::endl;
if (line.compare("quit") == 0)
return 1;
char* s = const_cast<char*>(line.c_str());
//std::cout << "begin reverse ... " << std::endl;
reverse_sentense(s);
std::cout << "the reverse is:\n" << s << std::endl;
}
return 0;
}