Created
June 4, 2023 12:02
-
-
Save kspalaiologos/3a2d2f8053cffd516665883030eed44b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
char ** split(char * string, char * delim) { | |
int count = 0; | |
char * tmp = string; | |
while (strstr(tmp, delim)) | |
tmp = strstr(tmp, delim) + strlen(delim), count++; | |
char ** result = malloc(sizeof(char *) * (count + 2)); | |
tmp = string; | |
for (int i = 0; i < count; i++) { | |
char * token = strstr(tmp, delim); | |
result[i] = malloc(sizeof(char) * (token - tmp + 1)); | |
strncpy(result[i], tmp, token - tmp); | |
result[i][token - tmp] = '\0'; | |
tmp = token + strlen(delim); | |
} | |
result[count] = malloc(sizeof(char) * (strlen(tmp) + 1)); | |
strcpy(result[count], tmp); | |
result[count + 1] = NULL; | |
return result; | |
} | |
void free_split(char ** res) { | |
for (int i = 0; res[i]; i++) | |
free(res[i]); | |
free(res); | |
} | |
int main() { | |
char * result = "This+-+Is+-+A+-+Message"; | |
char * delim = "+-+"; | |
char ** tokens = split(result, delim); | |
for (int i = 0; tokens[i] != NULL; i++) | |
printf("%s\n", tokens[i]); | |
free_split(tokens); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment