原题链接:2788. 按分隔符拆分字符串 - 力扣(LeetCode)
用C解该题的关键在于理解strtok函数的用法,函数原型如下:
char *strtok(char *str, const char *delim);
函数作用:以delim中的字符来分割str字符串,每次调用只会分割一次。
了解此,函数解题思路如下:对每一个字符串进行strtok分割,并将每一个子串加入结果数组中
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
char ** splitWordsBySeparator(char ** words, int wordsSize, char separator, int* returnSize){
char** res=(char**)malloc(sizeof(char*)*1000);
(*returnSize)=0;
for(int i=0;i<wordsSize;i++){
char* tok=strtok(words[i],&separator); // strtok两个参数都是地址
while(tok!=NULL){
res[(*returnSize)]=(char*)malloc(strlen(tok)+1);
strcpy(res[(*returnSize)++],tok);
tok=strtok(NULL,&separator);//继续分割,第一个参数就是NULL
}
}
return res;
}