C++ program to remove spaces from a string using String stream


As the given problem says, we need to remove spaces from the string using a string stream. As the name suggests, a string stream converts a string into a stream. It works similar to cin in C++. It associates a string object that can access the string buffer in which it is stored.

string s =" a for apple, b for ball";
res = solve(s);

With a string buffer, we will read each word one by one and then concatenate it into a new string which will be our answer.

Note − The class string stream is available in the sstream header file in c++, so we need to include it.

Let us look at some input/output scenarios

Assume the input taken by the function has no spaces in it, the output result achieved would be the same as the input −

Input: “Tutorialspoint”
Result: “Tutorialspoint”

Assume the input taken by the function has no spaces in it, the output result achieved would be the string void of all the spaces in it −

Input: “Tutorials Point”
Result: “TutorialsPoint”

Assume the input taken by the function has only spaces in it, the method fails to provide an output result −

Input: “ ”
Result: 

Algorithm

  • Consider an input string with characters.

  • The string is checked to not be empty and using stringstream keyword all the spaces present in the input are removed.

  • This process is done until the stringstream pointer reaches the end of line.

  • If it reaches end of line in the string, the program terminates.

  • The updated string is returned to the output result.

Example

For example, we have a string such as "a for apple, b for a ball," we need to convert that to "aforapple,bforball."

Following a detailed code of removing the spaces from string inputs to make it a stream of characters −

#include <iostream> #include <sstream> using namespace std; string solve(string s) { string answer = "", temp; stringstream ss; ss << s; while(!ss.eof()) { ss >> temp; answer+=temp; } return answer; } int main() { string s ="a for apple, b for ball"; cout << solve(s); return 0; }

Output

Aforapple,bforball

Example (Using getline)

We also have another approach using getline to solve the same query in C++.

#include <iostream> #include <sstream> using namespace std; string solve(string s) { stringstream ss(s); string temp; s = ""; while (getline(ss, temp, ' ')) { s = s + temp; } return s; } int main() { string s ="a for apple, b for ball"; cout << solve(s); return 0; }

Output

Aforapple,bforball

Conclusion

We see that using string stream, the string is stored in the buffer, and we can get the string word by word and concatenate it, removing spaces.

Updated on: 10-Aug-2022

695 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements