-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathrunlength.c
More file actions
54 lines (42 loc) · 891 Bytes
/
runlength.c
File metadata and controls
54 lines (42 loc) · 891 Bytes
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *catArgs(int argc, char *argv[])
{
size_t length = 0;
int i; for (i=1; i<argc; i++) {
length += strlen(argv[i]);
if (i < argc - 1) length++; /* space */
}
char *buf = malloc(length + 1);
*buf = '\0';
for (i=1; i<argc; i++) {
strcat(buf, argv[i]);
if (i < argc - 1) strcat(buf, " ");
}
return buf;
}
int main(int argc, char *argv[])
{
char *ptr, *buf;
unsigned int runlength = 0;
if (argc < 2) {
printf("Usage: %s string\n", argv[0]);
return 1;
}
ptr = buf = catArgs(argc, argv);
while (*ptr != '\0') {
static char last;
if (ptr == buf) /*if first character*/ last = *ptr;
if (*ptr == last) runlength ++;
else {
printf("%u\tx '%c'\n", runlength, last);
runlength = 1;
last = *ptr;
}
ptr++;
}
printf("%u\tx '%c'\n", runlength, *(ptr-1));
free(buf);
return 0;
}