R
Registered User
Hi experts,
I'm trying to write a program that replaces two or more consecutive
blanks in a string by a single blank.
Here's what I did:
#include <stdio.h>
#include <string.h>
#define MAX 80
int main()
{
char s[MAX];
int i, j;
fgets(s, MAX, stdin);
i=strlen(s);
while(i)
{
while (s[--i]!=' ' && i>0) /*Find the last space*/
;
j=i;
while (s[--j]==' ' && j>0) /*Go to the last non-space*/
; /*char before s*/
if (s[j]!=' ')
j++; /*Increment j so that s[j] is a space*/
if (j<i) /*If extra spaces have been found, remove*/
while (s) /*them by left shifting */
s[++j]=s[++i]; /*the characters on the right*/
i=j;
}
puts(s);
return 0;
}
The program works fine, but I have a feeling that I've made it
unnecessarily complicated.
Can anyone suggest ways on which I can improve upon the code? Is there
a better algorithm?
I'm trying to write a program that replaces two or more consecutive
blanks in a string by a single blank.
Here's what I did:
#include <stdio.h>
#include <string.h>
#define MAX 80
int main()
{
char s[MAX];
int i, j;
fgets(s, MAX, stdin);
i=strlen(s);
while(i)
{
while (s[--i]!=' ' && i>0) /*Find the last space*/
;
j=i;
while (s[--j]==' ' && j>0) /*Go to the last non-space*/
; /*char before s*/
if (s[j]!=' ')
j++; /*Increment j so that s[j] is a space*/
if (j<i) /*If extra spaces have been found, remove*/
while (s) /*them by left shifting */
s[++j]=s[++i]; /*the characters on the right*/
i=j;
}
puts(s);
return 0;
}
The program works fine, but I have a feeling that I've made it
unnecessarily complicated.
Can anyone suggest ways on which I can improve upon the code? Is there
a better algorithm?