Removing Spaces from a String using stringstream

Difficulty Level Easy
Frequently asked in Capgemini Hulu o9 solutions TCS

Problem Statement

In the “Removing Spaces from a String using stringstream” problem we have given a string “s”. Write a program that uses a string stream to remove spaces from the given string.

Input Format

The first and only one line containing a sentence/string “s”.

Output Format

The first line containing a string ans which denotes the final string after removing all white spaces in the given string.


  • 1<=|s|<=10^6
  • s[i] must be a lower case English alphabet or space ” “.


i really like the content of tutorialcup


Here we use the “eof()” function. C++ provides a special function, eof( ), that returns nonzero (meaning TRUE) when there are no more data to be read from anĀ input file stream, and zero (meaning FALSE) otherwise.

1. Store the given string in stringstream.

2. Now, empty the given string.

3. Extract each word from stringstream and concatenate them.

4. Print the final updated string.


C++ Program for Removing Spaces from a String using stringstream

#include <bits/stdc++.h> 
using namespace std; 
int main() 
  string s;
  getline(cin, s);
  stringstream t; 
  string temp; 
  return 0; 

Java Program for Removing Spaces from a String using stringstream

import java.util.HashMap;
import java.util.Scanner;
class sum
    public static void main(String[] args)
        Scanner sr = new Scanner(;
        String s = sr.nextLine();
        s=s.replaceAll(" ","");
a bc def

Complexity Analysis

Time Complexity

O(n) where n is the size of the given string “s”. Here we use the “stringstream” and “replaceAll” concept to remove all whitespaces.

Space Complexity

O(1) because we don’t store anything here. Simply update the given string and print it.

Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions
Core Java Interview Questions