Home C++ Tutorial Remove All Spaces from a String

Remove All Spaces from a String

by Anup Maurya
31 minutes read

In this article, you’ll learn to create a program in java, python and c++ to Remove All Spaces from a String.

Problem Statement:
Given a string, remove all spaces from the string and return it. 

Example 1:
Input: “This is a string”
Output: ThisisaString

Example 2:
Input: ” ”
Output: (empty string)

Python Program to Remove All Whitespaces from a String

def remove_spaces(text):
  """Removes spaces from a given string.

  Args:
      text: The input string.

  Returns:
      The string with all spaces removed.
  """

  return ''.join(text.split())

# Example usage
text = "This is a string"
result = remove_spaces(text)
print(result)  # Output: ThisisaString

Explanation:

  1. def remove_spaces(text):: This defines a function named remove_spaces that takes a string text as input.
  2. return ''.join(text.split()):
    • text.split(): Splits the input string text based on spaces, creating a list of words.
    • ''.join(): Joins the elements in the list (words) back into a single string with an empty string separator (''), effectively removing spaces.

Java Program to Remove All Whitespaces from a String

public class RemoveSpaces {

  public static String removeSpaces(String text) {
    StringBuilder sb = new StringBuilder();
    for (char c : text.toCharArray()) {
      if (c != ' ') {
        sb.append(c);
      }
    }
    return sb.toString();
  }

  public static void main(String[] args) {
    String text = "This is a string";
    String result = removeSpaces(text);
    System.out.println(result);  // Output: ThisisaString
  }
}

Explanation:

  1. public class RemoveSpaces {...}: Defines a class named RemoveSpaces.
  2. public static String removeSpaces(String text): Defines a static method removeSpaces that takes a string text as input and returns a string.
  3. StringBuilder sb = new StringBuilder();: Creates a StringBuilder object sb to efficiently build the new string.
  4. for (char c : text.toCharArray()) {...}: Iterates through each character c in the character array obtained from text.toCharArray().
  5. if (c != ' ') { sb.append(c); }: If the character c is not a space, it’s appended to the StringBuilder object sb.
  6. return sb.toString();: Returns the final string built in sb after iterating through all characters.

C++ Program to Remove All Whitespaces from a String

#include <iostream>
#include <string>
using namespace std;

string removeSpaces(const string& text) {
  string result;
  for (char c : text) {
    if (c != ' ') {
      result.push_back(c);
    }
  }
  return result;
}

int main() {
  string text = "This is a string";
  string result = removeSpaces(text);
  cout << result << endl;  // Output: ThisisaString
  return 0;
}

Explanation:

  1. #include <iostream> #include <string>: Includes necessary header files for input/output and string manipulation.
  2. string removeSpaces(const std::string& text): Defines a function removeSpaces that takes a constant reference to a string text as input and returns a string.
  3. string result;: Declares an empty string result to store the output.
  4. for (char c : text) {...}: Similar to Java, iterates through each character c in the input string using a range-based for loop.
  5. if (c != ' ') { result.push_back(c); }: If the character c is not a space, it’s pushed back to the

related posts

Leave a Comment

Enable Notifications OK No thanks