华为机试——子串分离
题目描述:
通过键盘输入任意一个字符串序列,字符串可能包含多个子串,子串以空格分隔。请编写一个程序,自动分离出各个子串,并使用’,’将其分割,并且在最后也补充一个‘,’并将子串存储;
例如:
输入“abc def gh i d”,结果将是abc,def,gh,i,d,
解题思路:
此题运用C++字符串控制流很好解决,不过需要包含头文件sstream,同时需要将输入的字符串与istringstream输入流对象绑定。
#include<iostream>
#include<string>
#include<vector>
#include<sstream>
using namespace std;
int main()
{
string inputStr,outputStr,str;
getline(cin,inputStr);
istringstream stream(inputStr);
while(stream>>str)
{
outputStr.append(str);
outputStr.push_back(',');
}
cout<<outputStr<<endl;
}