gpt4 book ai didi

c - 删除C中字符串中出现的每个\n

转载 作者:行者123 更新时间:2023-11-30 14:49:01 26 4
gpt4 key购买 nike

我已经看过这方面的教程和提示,但它们通常不适用于 C。这是我到目前为止所写的内容:

    printf("\nBefore removing: %s", an_name);
printf("%d", strlen(an_name));

for (i=0;i<strlen(an_name);i++){
printf("\nthe loop: %d",i);

if (an_name[i]!='\n'){
new_name[i] = an_name[i];
printf("\nthe loop: %d", i);
}
else{//when a \n is detected
new_name[i] = an_name[i+1];
i=i+1;
}
printf("\nAfter removing: %s\n", new_name);
printf("%d", strlen(an_name));
getchar();

return 0;
}

It does half the job. I want to remove the \n character and put all the new characters in a new string. But how?

最佳答案

您需要输入数组和输出数组的单独索引。否则,您永远不会将任何内容放入输出数组中跳过的换行符所在的位置,因此那里有一个未初始化的值。在您的测试中,它恰好包含 0,这是字符串终止符,因此它只打印了之前的所有内容。

循环完成后,您还需要在输出字符串的末尾添加一个空字节。

您可以使用 isspace() 来测试是否有空格。

#include <ctype.h>
#include <string.h>
#include <stdio.h>

int main(){
char an_name[20], new_name[20];
int i;

strcpy(an_name,"Ant\nho ny");

printf("\nBefore removing: %s\n", an_name);
printf("%ld", strlen(an_name));

int j = 0;
for (i=0;i<strlen(an_name);i++){
printf("\nthe loop: %d",i);

if(!isspace(an_name[i])){
new_name[j++] = an_name[i];
}
}
new_name[j] = '\0';

printf("\nAfter removing: %s\n", new_name);
printf("%ld", strlen(an_name));
getchar();

return 0;
}

输出:

Before removing: Ant
ho ny
9
the loop: 0
the loop: 1
the loop: 2
the loop: 3
the loop: 4
the loop: 5
the loop: 6
the loop: 7
the loop: 8
After removing: Anthony
9

关于c - 删除C中字符串中出现的每个\n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50073177/

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