Remove Spaces from a String

Problem Statement: Given a string, write a program to remove all the whitespaces from the string.

Examples:

Example 1:
Input: str = “Take you forward” 
Output: Takeyouforward
Explanation: After removing all the whitespaces Takeyouforward is the result

Example 2:
Input: str = “How are you doing”
Output: Howareyoudoing
Explanation: After removing all the whitespaces Howareyoudoing is the result

Solution

Disclaimer: Don’t jump directly to the solution, try it out yourself first.

Approach

Iterating through all the characters and finding if there is whitespace and if found skipping it and adding the next element to our string using a count variable.

The approach follows the following steps.

  1. Take a count variable that tells us the spaces seen sor far.
  2. Using a for loop, iterate through all the characters and check this condition.
    1. If the character at the current index is a whitespace or not, if not present then add the character to our string.
    2. Then increment the count to trace the whitespaces seen so far.

 Now after traversing all the characters and removing all the whitespaces we have our string without whitespace.

Code:

C++ Code

#include <iostream>

using namespace std;

string removeSpaces(char str[]) {
  int count = 0; // spaces seen so far

  for (int i = 0; str[i]; i++)
    if (str[i] != ' ') { // if whitespace is present
      str[count] = str[i]; // remove whitespace
      count++; // increment the count
    }

  str[count] = '\0';

  return str;
}

int main() {
  char str[] = "Take you forward";
  cout << removeSpaces(str);

  return 0;
}

Output:

Takeyouforward

Time Complexity: O(N)

Space Complexity: O(1)

Java Code

public class Main {
  static int removeSpaces(char[] str) {

    int count = 0; // to track spaces seen so far

    for (int i = 0; i < str.length; i++)
      if (str[i] != ' ') {
        str[count] = str[i];
        count++; // increment count
      }

    return count;
  }

  // Driver code
  public static void main(String[] args) {
    char[] str = "Take you forward ".toCharArray();
    int count = removeSpaces(str);
    System.out.println(String.valueOf(str).subSequence(0, count));
  }
}
    

Output:

Takeyouforward

Time Complexity: O(N)

Space Complexity: O(1)

Special thanks to Rushikesh Adhav for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article