2

文字列内の複数のスペースを単一のスペースに置き換えたいのですが、次のコードが機能しません。論理的な間違いは何ですか?

#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");
}
4

8 に答える 8

1

if(input[i]==' ' && (input[i+1]==' ' || input[i-1]==' '))

case " 1 3" : when i == 0 accses input[i-1] 範囲外

scanf("%d",&n);

改行のまま (input[0] <-- '\n')

修正する

scanf("%d%*c",&n);

#include <stdio.h>

char* uniq_spc(char* str){
    char *from, *to;
    int spc=0;
    to=from=str;
    while(1){
        if(spc && *from == ' ' && to[-1] == ' ')
            ++from;
        else {
            spc = (*from==' ')? 1 : 0;
            *to++ = *from++;
            if(!to[-1])break;
        }
    }
    return str;
}

int main(){
    char input[]= "  abc   de  f  ";

    printf("\"%s\"\n", uniq_spc(input));//output:" abc de f "
    return 0;
}
于 2013-05-28T11:01:33.000 に答える
1

必要以上に複雑にするのはなぜですか?strtok単一の空白をチェックし、それらを無視するために使用できます。次にstrcat、文字列を完全な文に連結するために使用できます。これで完了です。

これが私がやった方法です:

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

int main(void) {
    char *pch;
    char sentence[1000];
    char without[1000];

    printf("Sentence: ");
    fgets(sentence,1000, stdin);
    strtok(sentence, "\n"); // remove any newlines
    pch = strtok(sentence, " ");
    while(pch != NULL) {
      strcat(without, pch);
      strcat(without, " \0");
      pch = strtok(NULL, " ");
    }
    without[strlen(without)-1] = '\0'; // remove extra whitespace at the end
    printf("|%s|\n",without);
    return 0;
}
于 2015-10-26T22:15:31.023 に答える
0

次の for ループを修正する必要があります。あなたのforループの限界はあるべきでzあり、そうではないn

for(j=i;j<n;j++)
input[j]=input[j+1];

for(j=i;j<z;j++)
input[j]=input[j+1];

ところで:(文字scanf()を読み取る)最初の文字は改行(\n)です。scanf()この改行は decimal( %d)の最初から来ています

于 2013-05-28T11:23:13.700 に答える
0
#include<stdio.h>
#include<string.h>
int main(void)
    {
        char input[1000];
        int i=0;
        gets(input); 
        for(i=0;input[i]!='\0';i++)
        {
            if(input[i]!=' ' || input[i+1]!=' ')
                printf("%c",input[i]);
        }
        return 0;
    }
于 2016-04-06T11:09:52.230 に答える