gpt4 book ai didi

c - C语言中去除字符串中的空格

转载 作者:行者123 更新时间:2023-11-30 20:02:55 25 4
gpt4 key购买 nike

我不知道如何在不使用 stdio.h 和 stdlib.h 之外的任何库的情况下删除句子开头的空格。

#include <stdio.h>

int main()
{
char text[1000], result[1000];
int c = 0, d = 0;

printf("Enter some text\n");
gets(text);

while (text[c] != '\0') { // till the end of the string
if (text[c] == ' ') {
int temp = c + 1;
if (text[temp] != '\0') {
while (text[temp] == ' ' && text[temp] != '\0') {
if (text[temp] == ' ') {
c++;
}
temp++;
}
}
}
result[d] = text[c];
c++;
d++;
}
result[d] = '\0';

printf("Text after removing blanks\n%s\n", result);

return 0;
}

这段代码删除了句子中所有多余的空格。

示例:

输入: “这是我的程序。”

输出: “这是我的程序。”

预期输出: “这是我的程序。”

这段代码只留下一个空格,其中有更多空格,但我想删除开头的所有空格,就像预期的输出一样。

最佳答案

#include <stdio.h>

int main()
{
char text[1000], result[1000];
int c = 0, d = 0;

printf("Enter some text\n");
gets(text);

// no space at beginning
while(text[c] ==' ') { c++; }
while(text[c] != '\0'){
result[d++] = text[c++]; //take non-space characters
if(text[c]==' ') { result[d++] = text[c++]; } // take one space between words
while(text[c]==' ') { c++; } // skip other spaces
}
result[d] = '\0';

printf("Text after removing blanks\n%s\n", result);

return 0;
}

关于c - C语言中去除字符串中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57938824/

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