gpt4 book ai didi

c - 如何删除C中字符串中的空格?

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

我正在尝试下面的代码,但得到了错误的输出。例如我输入“a b c”,我希望结果是“abc”,但结果是一个汉字。

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
/* function prototype */
char *sweepSpace(char *sentence);
int main()
{
char str[80];
printf("Enter a string: ");//enter a string for example "a b c'
gets(str);
printf("Result: %s ", sweepSpace(str));//should print "abc"here
return 0;
}
char *sweepSpace(char *setence)
{
char b[80];
int i = 0;
while (*setence != NULL)
{
//if not reach the end
if (!isspace(*setence))
{
//if not a space
b[i] = *setence;//assign setence to b
i++;//increment
}
setence++;//pointer increment
}
b[i]= "\0";

return b;//return b to print
}

最佳答案

您正在返回一个本地数组变量 (b),当它在 main() 中被访问时会调用未定义的行为。

不要这样做。

在函数结束之前将新字符串复制回去:

strcpy(setence, b);

一些注意事项:

  1. 拼写为sentence
  2. 检查 '\0',而不是 NULL
  3. 在使用 isspace() 时转换为 unsigned int
  4. 结束符是'\0',不是"\0"

关于c - 如何删除C中字符串中的空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21986856/

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