-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsplitter.c
More file actions
85 lines (78 loc) · 2.08 KB
/
Copy pathsplitter.c
File metadata and controls
85 lines (78 loc) · 2.08 KB
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
#include "splitter.h"
enum bool { FALSE, TRUE };
typedef enum bool boolean;
boolean checkAllocated(char *pointer);
int countWordsOccurrences(char *string, char separator);
char **getAllocatedSpace(int number, char *string);
char **split(char *string, char separator);
boolean checkAllocated(char *pointer) { return pointer == NULL ? FALSE : TRUE; }
int countWordsOccurrences(char *string, char separator) {
char *z = malloc(sizeof(char) * strlen(string) + 1);
if (!checkAllocated(z)) {
perror("countWordsOccurences");
exit(EXIT_FAILURE);
}
strncpy(z, string, strlen(string));
int number = 0;
for (int i = 0; i < strlen(string); i++) {
char c = *z++;
if (c == separator || *z == '\0')
++number;
}
if (z) {
for (int i = 0; i < strlen(string); i++)
z--;
free(z);
}
return number;
}
char **getAllocatedSpace(int number, char *string) {
char **strings = malloc(strlen(string) * sizeof *strings);
for (int i = 0; i < number; i++) {
strings[i] = malloc(strlen(string) * sizeof *strings);
}
return strings;
}
char **split(char *string, char separator) {
int count = 0;
int inc = 0;
int number = countWordsOccurrences(string, separator);
int values[number];
char *p = malloc(sizeof(char) * strlen(string) + 1);
if (!checkAllocated(p)) {
perror("countWordsOccurences");
exit(EXIT_FAILURE);
}
strncpy(p, string, strlen(string));
char **strings = getAllocatedSpace(number, string);
if (!checkAllocated(*strings) || !checkAllocated(&(**strings))) {
perror("countWordsOccurences");
exit(EXIT_FAILURE);
}
while (*p) {
char current = *p++;
(*strings[count]++) = current;
inc++;
if (*p == separator) {
*(++strings[count]) = '\0';
values[count] = inc + 1;
count++;
inc = 0;
p++;
}
if (*p == '\0') {
*(++strings[count]) = '\0';
values[count] = inc + 1;
}
}
if (p) {
for (int i = 0; i < strlen(string); i++)
p--;
free(p);
}
for (int i = 0; i < number; i++) {
for (int j = 0; j < values[i]; j++)
strings[i]--;
}
return strings;
}