Write a C Program to Remove White Spaces from String

Write a C Program to Remove White Spaces from String

I had appeared for Riverbed placement interview. You can read my complete Riverbed interview experience. In one of the technical interview, an interviewer asked me to write code on paper.

Question to write code: You have given a string which includes multiple words. Write a C program to remove white spaces from string.

For example, if the input string is “Welcome to CSEstack”, output string should be “WelcometoCSEstack”.

It may seem difficult initially, but not much if you divide this question as two functions, we require.

  • Find the white spaces in the given string.
  • Shift left all the characters after white space.

C Program to Remove White Spaces from String

Below is a code implementation to remove white spaces from string in C and C++ language.

#include<stdio.h>

//Function Shift() takes string 
//and index of white space as inputs.
// It left-shifts all the character by one, 
//after given index of string

void Shift(char* str, int i)
{
    while(str[i+1])
    {
        str[i] = str[i+1];
        str++;
    }
    str[i] = '\0';
}

// Function findWhiteSpace() takes string as input. 
// It returns index of first white space in string.
int findWhiteSpace(char* str)
{
    int i=0;
    while(*str)
    {
        if(*str ==' ')
        return i;
        i++;
        str++;
    }
    return -1;
}

// Manager function to remove white spaces from string
int main()
{
    char str2[100] = "We Live and Breath Code";
    int i = -1;
    i = findWhiteSpace(str2);

    while(i!=-1)
    {
        Shift(str2, i);
        i = findWhiteSpace(str2);
    }

    printf("%s", str2);
}

Output :

"WeLiveandBreathCode".

Tip: In an interview, you may be asked to write any code. Keep explaining your code while writing. It will keep your interaction with the interviewer. It shows your problem-solving approach. Practice as many string manipulation programs.

There are many ways to remove white spaces from string. If you have a better solution, feel free to share in a comment.

Leave a Reply

Your email address will not be published. Required fields are marked *