-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathslicingString.c
More file actions
44 lines (41 loc) · 1.19 KB
/
slicingString.c
File metadata and controls
44 lines (41 loc) · 1.19 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
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int compare(const void *a, const void *b) {
return strcmp(*(const char**)a, *(const char**)b);
}
char** solution(const char* myString) {
char** answer = (char**)malloc(sizeof(char*));
int pos = 0;
const char *start = myString;
for (const char *p = myString;*p;p++) {
if (*p=='x') {
int len = p-start;
if (len>0) {
answer = (char**)realloc(answer, sizeof(char*)*(pos+2));
answer[pos] = (char*)malloc(sizeof(char)*(len+1));
strncpy(answer[pos], start, len);
answer[pos][len] = '\0';
pos++;
}
start = p+1;
}
}
int len = strlen(start);
if (len>0) {
answer = (char**)realloc(answer, sizeof(char*)*(pos+2));
answer[pos] = (char*)malloc(sizeof(char)*(len+1));
strncpy(answer[pos], start, len);
answer[pos++][len] = '\0';
}
qsort(answer, pos, sizeof(char*), compare);
return answer;
}
int main() {
const char* myString = "axbxcxdx";
char** answer = solution(myString);
while (*answer) {
printf("%s\n", *answer++);
}
return 0;
}