Program to remove spaces from a string | faceprep

Program to remove spaces from a string is discussed here. Given a string containing white spaces, the task is to remove all the spaces from the string and produce it as output.

For example, consider the following string

Input 1 :

“Hello All. Welcome to Face

Output 1:

HelloAll.WelcometoFace

Input 2:

F   a   c   e

Output 2:

Face

Algorithm to remove spaces from a string

  • Input the string.
  • Convert the string as character array.
  • Traverse the character array.
  • If the character encountered is not an empty space, print it.
  • If the character encountered is an empty space, skip the character.

Program to remove white spaces from a string is given below.

/* C program to remove spaces from a string */
#include<stdio.h>

char *remove_white_spaces(char *str)
{
int i = 0, j = 0;
while (str[i])
{
if (str[i] != ‘ ‘)
str[j++] = str[i];
i++;
}
str[j] = ‘\0’;
return str;
}

int main()
{
char str[50];
gets(str);
remove_white_spaces(str);
printf(“%s”,str);
return 0;
}

/* C++ program to remove spaces from a string */
#include <iostream>
using namespace std;

char *remove_white_spaces(char *str)
{
int i = 0, j = 0;
while (str[i])
{
if (str[i] != ‘ ‘)
str[j++] = str[i];
i++;
}
str[j] = ‘\0’;
return str;
}

int main()
{
char str[50];
cout << “\nEnter a string : “;
cin.getline(str,50);
remove_white_spaces(str);
cout << “Resultant String : “;
cout << str << endl;
return 0;
}

/* Java program to remove spaces from a string */
import java.util.*;

class Main
{
static int remove_white_spaces(char []str)
{
int count = 0;
for (int i = 0; i<str.length; i++)
if (str[i] != ‘ ‘)
str[count++] = str[i];

return count;
}

public static void main (String[] args)
{
char[] str = new char[50];
Scanner sc = new Scanner(System.in);
str = sc.nextLine().toCharArray();
int i = remove_white_spaces(str);
System.out.println(String.valueOf(str).subSequence(0, i));
}
}

# Python program to remove spaces from a string

def remove_white_spaces(string):
count = 0
list = []
for i in range(len(string)):
if string[i] != ‘ ‘:
list.append(string[i])

return toString(list)

def toString(List):
return ”.join(List)

str = input(“Enter a string : “)
print(remove_white_spaces(str) )

Output:

remove spaces from a string