-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreverse-words.c
64 lines (56 loc) · 1.14 KB
/
reverse-words.c
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
/* Reverse words delimeted by spaces or tabs */
#include <stdio.h>
static inline void swap(char *start, char *end)
{
char temp = *start;
*start = *end;
*end = temp;
return;
}
void reverse_chars(char *start, char *end)
{
while (end > start) {
swap(start, end);
start++, end--;
}
return;
}
/*
* Only spaces or tabs are treated as word delimeters.
* Everything else is treated as part of a word.
* The str argument is a NUL terminated C-string.
*/
void reverse_words(char *str)
{
char *start, *end;
start = str;
/* make sure that 'start' points to a
* non-space character */
while (*start == ' ' || *start == '\t')
start++;
end = start;
while (*end != '\0') {
end++;
if (*end == ' ' || *end == '\t') {
reverse_chars(start, end - 1);
end++;
/* Skip to next non-space character */
while (*end == ' ' || *end == '\t')
end++;
start = end;
}
}
end--;
reverse_chars(start, end);
reverse_chars(str, end);
return;
}
/* Test reverse words function */
int main()
{
char input_string[128];
fgets(input_string, sizeof(input_string), stdin);
reverse_words(input_string);
printf("%s\n", input_string);
return 0;
}