我正在尝试创建一个函数,该函数接受一个字符串,将其分割成单词并返回包含这些单词的数组。在“分割”函数中,除了malloc
之外,不允许使用任何预制函数。最后,我必须以以下格式设置我的函数:char **ft_split_whitespaces(char *str)
。
d this is me
s is me
s me
r
预期输出:
Hello
World
This
Is
Me
完整的代码如下:
#include <stdio.h>
#include <stdlib.h>
int count_words(char *str)
{
int i;
int word;
i = 0;
word = 1;
while(str[i]!='\0')
{
if(str[i]==' ' || str[i]=='\n' || str[i]=='\t'
|| str[i]=='\f' || str[i]=='\r' || str[i]=='\v')
word++;
i++;
}
return (word);
}
char **ft_split_whitespaces(char *str)
{
int index;
int size;
int index2;
char **arr;
index = 0;
index2 = 0;
size = count_words(str);
arr = (char **)malloc(size * sizeof(char));
if (arr == NULL)
return ((char **)NULL);
while (str[index])
{
if(str[index] == ' ')
{
index++;
value++;
index2++;
}
else
*(arr+index2) = (char*) malloc(index * sizeof(char));
*(arr+index2) = &str[index];
index++;
}
**arr = '\0';
return (arr);
}
int main()
{
char a[] = "Hello World This Is Me";
char **arr;
int i;
int ctr = count_words(a);
arr = ft_split_whitespaces(a);
for(i=0;i < ctr;i++)
printf("%s\n",arr[i]);
return 0;
}
ft_split_whitespaces
的代码应该如何知道返回的数组有多少项?末尾是否应该有一个NULL
值?(如果是这样,请不要忘记为该指针分配空间!) - David Schwartzft_split_whitespaces()
可以修改原始字符串(例如,在单词末尾插入零终止符并返回指向单词开头的指针数组,以避免为每个单词分配内存)吗?您还可以使用递归来避免count_words()
。 - Brendan