在C中用单个空格替换多个空格

Jas*_*S.P 2 c whitespace replace

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

#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");
}
Run Code Online (Sandbox Code Playgroud)

Som*_*ude 5

我会做这样的事情:

void replace_multi_space_with_single_space(char *str)
{
    char *dest = str;  /* Destination to copy to */

    /* While we're not at the end of the string, loop... */
    while (*str != '\0')
    {
        /* Loop while the current character is a space, AND the next
         * character is a space
         */
        while (*str == ' ' && *(str + 1) == ' ')
            str++;  /* Just skip to next character */

       /* Copy from the "source" string to the "destination" string,
        * while advancing to the next character in both
        */
       *dest++ = *str++;
    }

    /* Make sure the string is properly terminated */    
    *dest = '\0';
}
Run Code Online (Sandbox Code Playgroud)

当然,上面的函数要求你正确地终止你当前没有的字符串.

上面的函数是什么,基本上是将字符串复制到自身上.例外情况是当存在空间时,简单地丢弃多个空格.

由于函数修改了源字符串,因此不能在字符串文字中使用它.