Removing Spaces from a String using stringstream

Difficulty Level Easy
Frequently asked in Capgemini Hulu o9 solutions TCS
StringViews 2833

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.

Constraints

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

Example

i really like the content of tutorialcup
ireallylikethecontentoftutorialcup

Algorithm

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.

Implementation

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; 
  t<<s; 
  s=""; 
  while(!t.eof()) 
  { 
    t>>temp; 
    s=s+temp; 
  }
  cout<<s<<endl;
  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(System.in);
        String s = sr.nextLine();
        s=s.replaceAll(" ","");
        System.out.println(s);
    }
}
a bc def
abcdef

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.

Translate »