写一个暴力点写法
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main()
{
vector<string> ans;
string str;
getline(cin, str);
int begin = 0;//
int end = 0;
int sz = str.size();
string tmp;
while (end < sz)
{
if (str[begin] != '"')//如果不是'"',就是空格方案走
{
while (end < sz)
{
end++;
if (str[end] == ' ')//找到下一个空格
{
break;
}
}
tmp.clear();//请空原来的字符
for (int i = begin; i < end ; i++)
{
tmp.push_back(str[i]);//将没有‘”’的字符串存到tmp中
}
//tmp.push_back('\0');
ans.push_back(tmp);//然后将tmp尾加到ans中
end++;
begin = end;//重新下一轮
}
else//这是开头是有双引号的
{
begin++;
while (end < sz)
{
end++;
if (str[end] == '"')
{
break;
}
// tmp.push_back('\0');
}
tmp.clear();//请空原来的字符
for (int i = begin; i < end; i++)
{
tmp.push_back(str[i]);
}
ans.push_back(tmp);
end+=2;
begin = end;
}
}
int sz1 = ans.size();
cout<<sz1<<endl;
for (int i = 0; i < sz1; i++)
{
cout << ans[i] << endl;
}
return 0;
}
第二种就比教简单思想
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
vector<string> ans;
string tmp;
string str;
bool flag=false;
while(getline(cin, str))
{
for(int i=0;i<str.size();i++)
{
if(str[i]=='"')
{
flag=!flag;
}
else if(str[i]==' '&&!flag)
{
ans.push_back(tmp);
tmp="";
}
else
{
tmp+=str[i];
}
}
}
ans.push_back(tmp);
cout<<ans.size()<<endl;
for(int i=0;i<ans.size();i++)
{
cout<<ans[i]<<endl;
}
return 0;
}