用C中的单个空格替换多个空格 [英] Replace multiple spaces by single space in C

查看:53
本文介绍了用C中的单个空格替换多个空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用单个空格替换字符串中的多个空格,但是我的以下代码不起作用.逻辑错误是什么?

I want to repace multiple spaces in a string by single space, however my following code doesn't work. What's the logical mistake?

#include<stdio.h>
#include<string.h>
main()
{
char input[100];
int i,j,n,z=0;
scanf("%d",&n);
z=n;
for(i=0;i<n;i++)
scanf("%c",&input[i]);
for(i=0;i<n;i++)
{
    if(input[i]==' ' && (input[i+1]==' ' || input[i-1]==' '))
    {
        --z;
        for(j=i;j<n;j++)
        input[j]=input[j+1];
    }
}
for(i=0;i<z;i++)
    printf("%c",input[i]);
printf("\n");
}

推荐答案

scanf 给你带来了一些问题:它在输入长度后读取你给出的 \nn.因此,您将错过 for 循环退出后的最后一个字符.已经给出的答案已经足够好了.但如果你想遵循自己的逻辑,试试这个:

The scanf is giving you some problem: it reads the \n you give after inputting the length n. So, you will miss the last character since for loop exits. The already given answers are good enough. But if you want to follow your own logic, try this:

void main()
{
    char input[100];
    int i = 0,j,n = 0;
    while ((input[n] = getchar()) != '\n') {
        n++;
    }
    input[n] = '\0';
    while (i < n)
    {
        if(input[i]==' ' && (input[i+1]==' ' || input[i-1]==' '))
        {
            for(j=i;j<n;j++)
            input[j]=input[j+1];
            n--;
        }
        else
        {
            i++;
        }
    }
    printf("%s\n",input);
    printf("\n");
}

这篇关于用C中的单个空格替换多个空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆