You are here

C program remove spaces, blanks from a string

C program 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 the string
"C programming." It will remove spaces when they occur more than one time consecutively in string anywhere.

C programming code

  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5.    char text[1000], blank[1000];
  6.    int c = 0, d = 0;
  7.  
  8.    printf("Enter some text\n");
  9.    gets(text);
  10.  
  11.    while (text[c] != '\0') {
  12.       if (text[c] == ' ') {
  13.          int temp = c + 1;
  14.          if (text[temp] != '\0') {
  15.             while (text[temp] == ' ' && text[temp] != '\0') {
  16.                if (text[temp] == ' ') {
  17.                   c++;
  18.                }  
  19.                temp++;
  20.             }
  21.          }
  22.       }
  23.       blank[d] = text[c];
  24.       c++;
  25.       d++;
  26.    }
  27.  
  28.    blank[d] = '\0';
  29.  
  30.    printf("Text after removing blanks\n%s\n", blank);
  31.  
  32.    return 0;
  33. }

If you want you can copy blank into text string so that original string is modified.

Download Remove spaces program.

Output of program:
Remove spaces c program

C programming code using pointers

  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #define SPACE ' '
  5.  
  6. char *process(char*);
  7.  
  8. int main()
  9. {
  10.    char text[1000], *r;
  11.  
  12.    printf("Enter a string\n");
  13.    gets(text);
  14.  
  15.    r = process(text);
  16.  
  17.    printf("\"%s\"\n", r);
  18.    
  19.    free(r);    
  20.  
  21.    return 0;
  22. }
  23.  
  24. char *process(char *text) {
  25.    int length, c, d;
  26.    char *start;
  27.    
  28.    c = d = 0;
  29.    
  30.    length = strlen(text);
  31.  
  32.    start = (char*)malloc(length+1);
  33.    
  34.    if (start == NULL)
  35.       exit(EXIT_FAILURE);
  36.    
  37.    while (*(text+c) != '\0') {
  38.       if (*(text+c) == ' ') {
  39.          int temp = c + 1;
  40.          if (*(text+temp) != '\0') {
  41.             while (*(text+temp) == ' ' && *(text+temp) != '\0') {
  42.                if (*(text+temp) == ' ') {
  43.                   c++;
  44.                }  
  45.                temp++;
  46.             }
  47.          }
  48.       }
  49.       *(start+d) = *(text+c);
  50.       c++;
  51.       d++;
  52.    }
  53.    *(start+d)= '\0';
  54.    
  55.    return start;
  56. }