Home » Interview Questions » String Interview Questions » Removing spaces from a string using stringstream

Removing spaces from a string using stringstream


()

Given a string, write a function which uses stringstream to remove spaces from the given string

Example

INPUT
s = “I Love C++”

OUTPUT
“ILoveC++”

Algorithm

1. Store the given string in stringstream

2. Now, empty the given string

3. Extract each word from stringstream and concatenate them

C++ Program

#include <bits/stdc++.h>
using namespace std;


string removeSpaces(string s)
{
	stringstream ss;
	//to temporarily store each word
	string temp;
	//storing the complete string into string stream
	ss << s;
	//Making the string empty
	s = "";
	while(!ss.eof()) 
	{
		//extracting each word from stream
	    ss >> temp;
	    //concatenating
	    s = s + temp; 
	}
	return s;
}
int main()
{
	string s = "I Love C++";
	cout<<removeSpaces(s)<<endl;
}

Try It

 

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote Count

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

READ  Valid Number
Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions