-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathord_alphlong.c
102 lines (88 loc) · 1.67 KB
/
ord_alphlong.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define LOWER(a) (a >= 'A' && a <= 'Z' ? a + 0x20 : a)
static int size_of_word(char *s)
{
int i;
for (i = 0; s[i] && !strchr(" \t", s[i]); ++i);
return (i);
}
static int count_words(char *s)
{
int i;
int count;
for (i = count = 0; (unsigned)i < strlen(s); i += size_of_word(s + i), ++count)
while (strchr(" \t", s[i]))
++i;
return (count);
}
static void swap(char **a, char **b)
{
char *tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
static void sort(char **tab)
{
int i;
int j;
for (i = 0; tab[i]; ++i)
for (j = i; tab[j]; ++j)
{
if (strlen(tab[j]) < strlen(tab[i]))
swap(&tab[i], &tab[j]);
else if (strlen(tab[j]) == strlen(tab[i])
&& strcasecmp(tab[i], tab[j]) > 0)
swap(&tab[i], &tab[j]);
}
}
static void display(char **tab)
{
int i;
i = -1;
while (tab[++i])
{
write(1, tab[i], strlen(tab[i]));
if (tab[i + 1] == NULL)
write(1, "\n", 1);
else if (strlen(tab[i]) == strlen(tab[i + 1]))
write(1, " ", 1);
else
write(1, "\n", 1);
}
}
static void parse(char *s)
{
char **tab;
int words;
int i;
int j;
words = count_words(s);
if (!(tab = malloc((sizeof(char *) * (1 + words)))))
return ;
tab[words] = NULL;
i = -1;
j = -1;
while (s[++i])
{
if (!i || ((s[i - 1] == 0 || strchr(" \t", s[i - 1]))
&& !strchr(" \t", s[i])))
tab[++j] = s + i;
else if (strchr(" \t", s[i]))
s[i] = 0;
}
sort(tab);
display(tab);
free(tab);
}
int main(int ac, char **av)
{
if (ac != 2)
return (write(1, "\n", 1));
while (strchr(" \t", *av[1]))
++av[1];
parse(av[1]);
return (0);
}