-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinplace.c
53 lines (44 loc) · 1.12 KB
/
inplace.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
#include <stdio.h>
#include <string.h>
/*
* Given a string of words delimited by spaces,
* reverse the words in string.
* For example, given "hello world here", return "here world hello"
*
* Follow-up:
* given a mutable string representation,
* can you perform this operation in-place?
*/
int
main(int ac, char **av)
{
char *original, *copy;
int i, j, max;
original = av[1];
copy = strdup(original); // in case av[i] is not writable
printf("Original string: \"%s\"\n", original);
// reverse the entire string in-place
for (i = 0, j = strlen(copy) - 1; i < j; i++, j--) {
char tmp = copy[i];
copy[i] = copy[j];
copy[j] = tmp;
}
printf("Reversed string: \"%s\"\n", copy);
// reverse individual space-separated words in-place
max = strlen(copy);
for (i = 0; i < max; ) {
int itmp, jtmp;
// find end of word that begins at index i
for (j = i; copy[j] != ' ' && j < max; j++)
;
jtmp = j - 1;
for (itmp = i; itmp < jtmp; itmp++, jtmp--) {
char tmp = copy[itmp];
copy[itmp] = copy[jtmp];
copy[jtmp] = tmp;
}
i = j+1; // skip space
}
printf("Reversed string: \"%s\"\n", copy);
return 0;
}