I am learning C and have to code a program that:
- reads an amount of chars from stdin and stores them in an array;
- substitute any two or more consecutive spaces (' ') for only one;
- write back the array.
So far I have done the following:
#include <stdio.h>
#define DIM 100
int main(int argc, char **argv)
{
char mainArray [DIM]={'\0'};
int auxArray [DIM];
int i, m, n, c, l;
printf("Enter a string containing two or more consecutive spaces:\n");
/* Read string from stdin */
do
{
mainArray[i]=getchar();
++i;
} while ((mainArray[i-1] != '\n') && (i < DIM-1));
/* Place the string terminator '\0' */
if (i < DIM)
mainArray[i]='\0';
else
mainArray[DIM-1]='\0';
l=i;
/* My substitution algorithm */
for (i=0 ; mainArray[i] != '\0' ; ++i)
{
if (mainArray[i] == ' ')
{
if (mainArray[i] == mainArray[i+1])
{
auxArray[m]=i;
++m;
}
}
}
for (i=0 ; i < m ; ++i)
{
for (c=auxArray[i] ; c < l-1 ; ++c)
mainArray[n]=mainArray[n+1];
}
/* Display the corrected string */
for (i=0 ; mainArray[i] != '\0' ; ++i)
printf("%c", mainArray[i]);
return 0;
}
As an example, entering the string "a_long_time_ago___in_a_galaxy__far____,_far_away.." would produce "a_long_time_ago_in_a_galaxy_far_,_far_away.."
For the substitution algorithm I thought that one possiblity could be to store the positions of the spaces in excess, and then delete the spaces in the main array through the auxiliary array.
I am sure I am making some amateaur mistake. Also, how can the code be optimized in your opinion?
Thank you in advance.