gpt4 book ai didi

在 C 中使用指针创建无空格字符串

转载 作者:行者123 更新时间:2023-11-30 20:18:44 24 4
gpt4 key购买 nike

我正在尝试编写一个代码来创建一个没有空格的字符串。但我的代码不起作用。

#include<stdio.h>
#include<stdbool.h>

bool SpaceDetect(char c)
{
if (c == ' '|| c == '\n' || c == '\t')
return true;
return false;
}

char *NoSpacer(char* s)
{
char* cs = s;
while (*s != '\0')
{
if(SpaceDetect(*s))
{
s++;
continue;
}
*cs = *s;
cs++;
s++;
}
*cs = '\0';
return cs;
}

int main ()
{
char test[] = " this is a test for me";
printf("String with space is : %s\r\n", test);
printf("Sting with no space is: %s\r\n", NoSpacer(test));
return 0;
}
<小时/>

输出如下:

Stinng with space is : this is a test for me
Segmentation fault (core dumped)

最佳答案

这个

cs++; /* this changes cs initial address where it points */

使用 cs[index] 代替 cs++ 并递增 index 并将 s 的内容存储到cs 不带空格。

例如

char *NoSpacer(char* s) {
char* cs = s;
int index = 0;
while (*s != '\0') {
if(SpaceDetect(*s)) {
s++;
continue;
}
cs[index] = *s; /* this is correct way */
index+=1;
//cs++; /* this is the problem */
s++;
}
cs[index] = '\0';
return cs;
}

关于在 C 中使用指针创建无空格字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53028433/

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