我需要拆分一個字符串,其中有空格(例如,字符串:Hello this is an example string.
)成一個單詞數組。我不確定我在這裏錯過了什麼,我也很好奇以什麼來測試這個功能最好的辦法是,唯一允許的庫函數是malloc
。C - 在空白處拆分一個字符串
任何幫助表示讚賞!
#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()'? –
或'strtok_s' /'strtok_r'? – Useless
你現在在做「魚」嗎? – Gam