Solution to removing spaces from a string is already posted here. In this article another solution using stringstream is discussed.
Algorithm:
1. Enter the whole string into stringstream.
2. Empty the string.
3. Extract word by word and concatenate to the string.
Program 1: Using EOF.
CPP
#include <bits/stdc++.h>
using namespace std;
string removeSpaces(string str)
{
stringstream ss;
string temp;
ss << str;
str = "" ;
while (!ss.eof()) {
ss >> temp;
str = str + temp;
}
return str;
}
int main()
{
string s = "This is a test" ;
cout << removeSpaces(s) << endl;
s = "geeks for geeks" ;
cout << removeSpaces(s) << endl;
s = "geeks quiz is awesome!" ;
cout << removeSpaces(s) << endl;
s = "I love to code" ;
cout << removeSpaces(s) << endl;
return 0;
}
|
OutputThisisatest
geeksforgeeks
geeksquizisawesome!
Ilovetocode
Time complexity: O(n) where n is length of string
Auxiliary space: O(n)
Program 2: Using getline().
CPP
#include <bits/stdc++.h>
using namespace std;
string removeSpaces(string str)
{
stringstream ss(str);
string temp;
str = "" ;
while (getline(ss, temp, ' ' )) {
str = str + temp;
}
return str;
}
int main()
{
string s = "This is a test" ;
cout << removeSpaces(s) << endl;
s = "geeks for geeks" ;
cout << removeSpaces(s) << endl;
s = "geeks quiz is awesome!" ;
cout << removeSpaces(s) << endl;
s = "I love to code" ;
cout << removeSpaces(s) << endl;
return 0;
}
|
OutputThisisatest
geeksforgeeks
geeksquizisawesome!
Ilovetocode
Time complexity: O(n)
Auxiliary Space: O(n)
This article is contributed by Nishant. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.