C Program to Remove White Spaces from a String

Write a C program to remove white spaces from a string using a for loop. In this C example, for loop iterate string from the first character to last, and the if statement check for the empty or white space character. If True, the compiler will skip that character from storing it into the array.

#include <stdio.h>

int main()
{
    char str[100];
    int i, j = 0;
    
    printf("Enter String to Remove White Spaces = ");
    gets(str);

    printf("String before Removing Empty Spaces = %s\n", str);
    for(i = 0; str[i] != '\0'; i++)
    {
        str[i] = str[i + j];

        if(str[i] == ' ' || str[i] == '\t')
        {
            j++;
            i--;
        }
    }
    printf("String after Removing Empty Spaces  = %s\n", str);
}
C Program to Remove White Spaces from a String

It is another way of writing a c program for removing the white spaces from a string. Here, we used the nested for loops.

#include <stdio.h>
#include<string.h>

int main()
{
    char str[100];
    int i, j = 0;
    
    printf("Enter String to Remove White Spaces = ");
    gets(str);

    int len = strlen(str);

    printf("String before Removing Empty Spaces = %s\n", str);
    for(i = 0; i < len; i++)
    {
        if(str[i] == ' ' || str[i] == '\t')
        {
            for(j = i; j < len; j++)
            {
                str[j] = str[j + 1];
            }
            len--;
        }
    }
    printf("String after Removing Empty Spaces  = %s\n", str);

    return 0;
}
Enter String to Remove White Spaces = c programs
String before Removing Empty Spaces = c programs
String after Removing Empty Spaces  = cprograms


Enter String to Remove White Spaces = learn c
String before Removing Empty Spaces = learn c
String after Removing Empty Spaces  = learnc

C program to remove all the white spaces or blank spaces from a string using a while loop.

#include <stdio.h>

int main()
{
    char str[100];
    int i, j, k;
    
    printf("Enter String to Remove White Spaces = ");
    gets(str);

    printf("String before Removing Empty Spaces = %s\n", str);
    i = 0;

    while(str[i] != '\0')
    {
        k = 0;
        if(str[i] == ' ' || str[i] == '\t')
        {
            j = i;
            while(str[j - 1] != '\0')
            {
                str[j] = str[j + 1];
                j++;
            }
            k = 1;
        }
        if(k == 0)
        {
            i++;
        }
    }
    printf("String after Removing Empty Spaces  = %s\n", str);
}
Enter String to Remove White Spaces = c programming exmaples
String before Removing Empty Spaces = c programming exmaples
String after Removing Empty Spaces  = cprogrammingexmaples