我需要将一个字符串按空格分割(例如字符串:
任何帮助都将不胜感激!
Hello this is an example string.
),并将其拆分为单词数组。我不确定我漏掉了什么,也想知道测试此函数的最佳方法。唯一允许使用的库函数是malloc
。任何帮助都将不胜感激!
#include <stdlib.h>
char **ft_split(char *str) {
int wordlength;
int wordcount;
char **wordbank;
int i;
int current;
current = 0;
wordlength = 0;
//while sentence
while (str[wordlength] != '\0') {
//go till letters
while (str[current] == ' ')
current++;
//go till spaces
wordlength = 0;
while (str[wordlength] != ' ' && str[wordlength] != '\0')
wordlength++;
//make memory for word
wordbank[wordcount] = malloc(sizeof(char) * (wordlength - current + 1));
i = 0;
//fill wordbank current
while (i < wordlength - current) {
wordbank[wordcount][i] = str[current];
i++;
current++;
}
//end word with '\0'
wordbank[wordcount][i] = '\0';
wordcount++;
}
return wordbank;
}
strchr()
函数? - Iharob Al Asimistrtok_s
/strtok_r
? - Useless