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");
}
You have to fix the following for loop. the limit of your for loop should be
z
and notn
by
BTW: the fist charachter get by your
scanf()
(which read charachters) is newline (\n
). this newline come from the firstscanf()
of decimal(%d
)The
scanf
is giving you some problem: it reads the\n
you give after inputting the lengthn
. So, you will miss the last character sincefor
loop exits. The already given answers are good enough. But if you want to follow your own logic, try this:You cant try this simple code:
if(input[i]==' ' && (input[i+1]==' ' || input[i-1]==' '))
case " 1 3" : when i == 0 accses input[i-1] Out-of-Bounds
scanf("%d",&n);
remain newline, (input[0] <-- '\n')
fix to
scanf("%d%*c",&n);