C++ 分割字符串函数,并且返回vector

2014-11-24 00:59:25 · 作者: · 浏览: 4
#include
#include
#include
using namespace std;
vector split(const string &str)
{
vector result;
int i=0;
int j=0;
//去除字符串左边所有空格
while(str[i]==' ')
{
i++;
}
j=i;
//遍历字符串
while(i
{
if(str[j]==' ' || str[j]=='\0')
{
result.push_back(str.substr(i,j-i));
j++;
i=j;
}
else
{
j++;
}
}
return result;
}
void out(vector &result)
{
for(int i=0;i
{
cout<
}
}
int main()
{
string line="hello welcome to see us!";
vector result=split(line);
out(result);
return 0;
}