从字符串删除空格的解决方案已经发布在这里。在本文中,讨论了另一个使用stringstream的解决方案。
算法
1. Enter the whole string into stringstream.
2. Empty the string.
3. Extract word by word and concatenate to the string.
程序1:使用EOF。
// C++ program to remove spaces using stringstream
#include
using namespace std;
// Function to remove spaces
string removeSpaces(string str)
{
stringstream ss;
string temp;
// Storing the whole string
// into string stream
ss << str;
// Making the string empty
str = "";
// Running loop till end of stream
while (!ss.eof()) {
// Extracting word by word from stream
ss >> temp;
// Concatenating in the string to be
// returned
str = str + temp;
}
return str;
}
// Driver function
int main()
{
// Sample Inputs
string s = "This is a test";
cout << removeSpaces(s) << endl;
s = "geeks for geeks";
cout << removeSpaces(s) << endl;
s = "geeks quiz is awsome!";
cout << removeSpaces(s) << endl;
s = "I love to code";
cout << removeSpaces(s) << endl;
return 0;
}
输出:
Thisisatest
geeksforgeeks
geeksquizisawsome!
Ilovetocode
程序2:使用getline()。
// C++ program to remove spaces using stringstream
// and getline()
#include
using namespace std;
// Function to remove spaces
string removeSpaces(string str)
{
// Storing the whole string
// into string stream
stringstream ss(str);
string temp;
// Making the string empty
str = "";
// Running loop till end of stream
// and getting every word
while (getline(ss, temp, ' ')) {
// Concatenating in the string
// to be returned
str = str + temp;
}
return str;
}
// Driver function
int main()
{
// Sample Inputs
string s = "This is a test";
cout << removeSpaces(s) << endl;
s = "geeks for geeks";
cout << removeSpaces(s) << endl;
s = "geeks quiz is awsome!";
cout << removeSpaces(s) << endl;
s = "I love to code";
cout << removeSpaces(s) << endl;
return 0;
}
// Code contributed by saychakr13
输出:
Thisisatest
geeksforgeeks
geeksquizisawsome!
Ilovetocode
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。