Last active
July 8, 2024 09:12
-
-
Save iTrooz/85c4d2d13de901ab1a3ff080278ce70a to your computer and use it in GitHub Desktop.
Manual implemenation of a split() function in C
This file contains hidden or 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<stdlib.h> | |
#include<stdio.h> | |
#define bool short | |
#define false 0 | |
#define true 1 | |
bool my_contains(char *charset, char c) { | |
for (int i = 0; charset[i] != '\0'; i++) { | |
if (charset[i] == c) { | |
return true; | |
} | |
} | |
return false; | |
} | |
void my_strcpy(char *dst, char *src, int length) { | |
for (int i = 0; i < length; i++) { | |
dst[i] = src[i]; | |
} | |
} | |
int my_strlen(char *str) { | |
int l = 0; | |
while (str[l] != '\0') { | |
l++; | |
} | |
return l; | |
} | |
char **ft_split(char *str, char *charset) { | |
char **output = (char **)malloc(sizeof(char *) * my_strlen(str)); | |
int outputIndex = 0; | |
int inputStartIndex = 0; | |
int inputEndIndex = 0; | |
while (1==1) { | |
if (my_contains(charset, str[inputEndIndex]) || str[inputEndIndex] == '\0') { // check if separator or end of string | |
// only append to output if non-zero length | |
if(inputEndIndex - inputStartIndex > 0) { | |
// append to output | |
output[outputIndex] = (char *)malloc(sizeof(char) * (inputEndIndex - inputStartIndex + 1)); | |
my_strcpy(output[outputIndex], str + inputStartIndex, inputEndIndex - inputStartIndex); | |
output[outputIndex][inputEndIndex - inputStartIndex] = 0; | |
outputIndex++; | |
} | |
inputStartIndex = inputEndIndex+1; | |
} | |
// break at the end of the string | |
if(str[inputEndIndex] == '\0') { | |
break; | |
} | |
inputEndIndex++; | |
} | |
// reallocate to only use the minimum memory necessary | |
char **newOutput = (char **)malloc(sizeof(char *) * (outputIndex)); | |
for (int i = 0; i < outputIndex; i++) { | |
newOutput[i] = output[i]; | |
} | |
newOutput[outputIndex] = 0; | |
free(output); | |
return newOutput; | |
} | |
int main() { | |
char *str = "Hello, world!world!world!world!hey"; | |
char *charset = ", !"; | |
char **output = ft_split(str, charset); | |
for (int i = 0; output[i] != NULL; i++) { | |
printf("PART=%s\n", output[i]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment