gpt4 book ai didi

c - 返回字符串中的第 i 个单词

转载 作者:太空宇宙 更新时间:2023-11-04 08:20:41 24 4
gpt4 key购买 nike

实现 char * ithword(char * str, int i) 将返回 str 中的第 i 个单词。这些词是字母数字的,由非字母数字字符分隔。该函数将为返回的单词分配内存,并返回指向它的指针。

我的代码:

char *ithword(char * str, int i)
{
/* declarations */
char *der = malloc(100 * sizeof(int));
int nw, state, j, counter;
state = 0;
nw = 0;
counter =0 ;

for(j = 0; (nw <= i) || (j < sizeof(str)); j++) {
char c = str[j];
if (c == '\0')
return der;
if (isalnum(c) == 0) {
state = 0;
continue;
}
if (state == 0) {
state = 1;
nw++;
}
if (nw == i) {
der[counter]=c;
counter++;
}
}
return der;
}
int main()
{
char *p = malloc(101);
p = ithword("bcd&acd*abc",3);
printf("%s",p);
}

最佳答案

我看到的一些问题,我添加了评论。

char *ithword(char * str, int i)
{
char *der = (char *)malloc(101); # Why sizeof(int) when it has to store characters.
memset(der ,0, 101); # Always memset a malloc allocated memory else garbage value would be printed.
int nw, state, j, counter;
state = 0;
nw = 0;
counter =0 ;

for(j = 0; (nw <= i) || (j < sizeof(str)); j++) {
char c = str[j];
if (c == '\0')
return der;
if (isalnum(c) == 0) {
state = 0;
continue;
}
if (state == 0) {
state = 1;
nw++;
}
if (nw == i) {
der[counter]=c;
counter++;
}
}
der[counter] = '\0'; # The output string has to be null terminated else all the characters would be printed from the memory location until a null is encountered.
return der;
}

int main()
{
char *p = NULL; # Do not allocate here. What you did would create dangling pointer because you have allocated it and then pointed it to some other location.
p = ithword("bcd&acd*abc",3);
printf("%s",p);
return 0; # Return an exit code (0) since it has to return an int.
}

再次指出问题:

  • main() 中的悬挂指针。
  • 最好根据定义从 main() 返回退出代码。
  • 如果内存是通过 malloc 分配的,则始终 memset 内存,否则它将具有垃圾值,这可能导致不确定的输出。
  • 始终以 null 终止自创建的字符串,因为在打印时编译器会打印所有字符,直到遇到“\0”。
  • 建议:不要盲目分配 101,找到输入字符串 str 的长度并分配该大小,以便它可以处理小字符串和大字符串。

关于c - 返回字符串中的第 i 个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33558911/

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