I have programmed a function to split strings, and it gives the expected output. I am looking forward to write better code and I was told here is a good place to start.
Here's my program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **split(char *str) {
int str_length = 0;
int i = 0;
int separator_count = 0;
while (str[i] != '\0') {
if (str[i] == ' ') {
separator_count++;
}
i++;
}
char **word_array;
word_array = malloc((separator_count + 2) * sizeof(char *));
int word_len = 0;
int separator_index = 0;
int b = 0; //to iterate over "str"
for (int a = 0; a < (separator_count + 2); a++) {
word_len = 0;
while (str_length < strlen(str) + 1) {
str_length++;
if (str[b] == ' ' || str[b] == '\0') {
separator_index = b;
word_array[a] = malloc(word_len * sizeof(char));
int word_depth = 0;
for (int c = (separator_index - word_len); c < separator_index; c++) {
chrctr = str[c];
word_array[a][word_depth] = str[c];
word_depth++;
}
word_array[a][word_len] = '\0'; //terminate found and stored word with null charachter
word_len = 0; //reset word length counter to 0
b++; //skip to next charachter
break; // break to go to next index of word_array
}
word_len++;
b++;
}
}
word_array[separator_count + 2] = NULL;
return word_array;
}
int main() {
char s[] = "A complete toolkit for building search into your product."; //test string
char **ss = split(s);
for (int i = 0; i < sizeof(ss); i++) { //here is the problem, and doing sizeof(ss)/sizeof(ss[0])=1 !!
for (int j = 0; j < strlen (ss[i]); j++) {
printf("%c", ss[i][j]);
}
printf ("\n");
}
}
Please comment with any advice or remarks on how to make this better.