C Program Remove Spaces, Blanks From A String

Share

C code to remove spaces or excess blanks from a string, For example consider the string

“c programming”

There are two spaces in this string, so our program will print a string

“c programming”. It will remove spaces when they occur more than one time consecutively in string anywhere.

C programming code :

#include <stdio.h>

int main()
{
   char text[100], blank[100];
   int c = 0, d = 0;

   printf("Enter some textn");
   gets(text);

   while (text[c] != '')
   {
      if (!(text[c] == ' ' && text[c+1] == ' ')) {
        blank[d] = text[c];
        d++;
      }
      c++;
   }

   blank[d] = '';

   printf("Text after removing blanksn%sn", blank);

   return 0;
}

C Programming Code Using Pointers :

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define SPACE ' '

main()
{
   char string[100], *blank, *start;
   int length, c = 0, d = 0;

   printf("Enter a stringn");
   gets(string);

   length = strlen(string);

   blank = string;

   start = (char*)malloc(length+1);

   if ( start == NULL )
      exit(EXIT_FAILURE);

   while(*(blank+c))
   {
      if ( *(blank+c) == SPACE && *(blank+c+1) == SPACE )
      {}
      else
      {
         *(start+d) = *(blank+c);
	 d++;
      }
      c++;
   }
   *(start+d)='';

   printf("%sn", start);

   free(start);     

   return 0;
}

Compiler used:

GCC

Output of program:

get blanks in c program



Share