-
Notifications
You must be signed in to change notification settings - Fork 0
/
1.2 Reverse String.cpp
58 lines (53 loc) · 1.09 KB
/
1.2 Reverse String.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
// Reverse a string word-wise,
// different from the original question
#include <stdio.h>
void reverse_letter(char *start, char *end)
{
while (start < end)
{
char temp = *start;
*start++ = *end;
*end-- = temp;
}
}
void reverse(char *str)
{
if (!str)
return;
// loop invariant: [start, end) will be reversed as a word
char *start = str;
char *end = start;
while (1)
{
if (*end != ' ' && *end != '\0')
{
++end;
}
else if (*end == ' ')
{
if (start < end)
{
reverse_letter(start, end - 1);
}
++end;
start = end;
}
else if (*end == '\0')
{
if (start < end)
{
reverse_letter(start, end - 1);
}
reverse_letter(str, end - 1);
break;
}
}
}
int main(int argc, char const *argv[])
{
char str[20] = " a test case\0";
printf("%s\n", str);
reverse(str);
printf("%s\n", str);
return 0;
}