当前位置:编程学习 > C/C++ >>

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

#include <vector>
#include <iostream>
#include <string>
using namespace std;
 
 
vector<string> split(const string &str)
{
vector<string> result;
int i=0;
int j=0;
//去除字符串左边所有空格
while(str[i]==' ')
{
i++;
}
j=i;
//遍历字符串
while(i<str.length())
{
if(str[j]==' ' || str[j]=='\0')
{
result.push_back(str.substr(i,j-i));
j++;
i=j; 
}
else
{
j++;
}
 
}
return result;
}
void out(vector<string> &result)
{
for(int i=0;i<result.size();i++)
cout<<result[i]<<endl;
}
}
int main()
{
string line="hello welcome to see us!";
vector<string> result=split(line);
 
 
out(result);
return 0;
}
 
补充:软件开发 , C++ ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,