Skip to content

Instantly share code, notes, and snippets.

@hamza-cskn
Created February 19, 2023 07:15
Show Gist options
  • Save hamza-cskn/0188774d2480101d9a6fa32ca2c31d37 to your computer and use it in GitHub Desktop.
Save hamza-cskn/0188774d2480101d9a6fa32ca2c31d37 to your computer and use it in GitHub Desktop.
split exercise for école thirty four
#include <stdlib.h>
#include <printf.h>
int is_seperator(char c) {
return (c == '\0' || c == ' ' || c == '\n');
}
int word_length(char *str) {
int i;
i = 0;
while (!is_seperator(str[i]))
i++;
return i;
}
char *ft_duplicate(char *str, int size) {
int i;
char *res;
res = malloc(sizeof(char *) * size);
if (!res)
return 0;
i = 0;
while (i < size - 1) {
res[i] = str[i];
i++;
}
res[i] = 0;
return res;
}
int count_words(char *str) {
int i;
int count;
count = 0;
while (*str) {
i = 0;
while (str[i] && is_seperator(str[i]))
i++;
if (str[i])
count++;
while (str[i] && !is_seperator(str[i]))
i++;
str += i;
}
return count;
}
char **ft_split(char *str) {
int word_amount = count_words(str);
char **result = malloc(sizeof (char *) * word_amount);
int i;
int word_index = 0;
while (*str) {
i = 0;
while (str[i] && is_seperator(str[i]))
i++;
if (str[i]) {
int size = word_length(str + i) + 1;
result[word_index++] = ft_duplicate(str + i, size);
}
while (str[i] && !is_seperator(str[i]))
i++;
str += i;
}
return result;
}
int main() {
char test[] = " this is a test ";
char **map = ft_split(test);
printf("1 -> %s\n", map[0]);
printf("2 -> %s\n", map[1]);
printf("3 -> %s\n", map[2]);
printf("4 -> %s\n", map[3]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment