gpt4 book ai didi

C - 在空格处拆分字符串

转载 作者:行者123 更新时间:2023-12-04 04:44:29 26 4
gpt4 key购买 nike

我需要在有空格的地方拆分一个字符串(ex string: Hello this is an example string. into an array of words. 我不确定我在这里遗漏了什么,我我也很好奇测试此函数的最佳方法是什么。唯一允许的库函数是 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;
}

最佳答案

您的代码中存在多个问题:

  • 您没有为 wordbank 分配指向的数组,取消引用未初始化的指针具有未定义的行为。
  • 您扫描字符串的方法有问题:您在循环内重置了 wordlength,因此您一直从字符串的开头重新扫描。
  • 您应该在数组中为尾随空指针分配一个额外的条目,以向调用者指示数组的结尾。

修改后的版本:

#include <stdlib.h>

char **ft_split(const char *str) {
size_t i, j, k, wordcount;
char **wordbank;

// count the number of words:
wordcount = 0;
for (i = 0; str[i]; i++) {
if (str[i] != ' ' && (i == 0 || str[i - 1] == ' ')) {
wordcount++;
}
}

// allocate the word array
wordbank = malloc((wordcount + 1) * sizeof(*wordbank));
if (wordbank) {
for (i = k = 0;;) {
// skip spaces
while (str[i] == ' ')
i++;
// check for end of string
if (str[i] == '\0')
break;
// scan for end of word
for (j = i++; str[i] != '\0' && str[i] != ' '; i++)
continue;
// allocate space for word copy
wordbank[k] = p = malloc(i - j + 1);
if (p == NULL) {
// allocation failed: free and return NULL
while (k-- > 0) {
free(wordbank[k]);
}
free(wordbank);
return NULL;
}
// copy string contents
memcpy(p, str + j, i - j);
p[i - j] = '\0';
}
// set a null pointer at the end of the array
wordbank[k] = NULL;
}
return wordbank;
}

关于C - 在空格处拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45740032/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com