string的split函数,求解

pengxincz 2010-04-03 02:33:23
最近从C#过度到C++, 想使用C#里的一个string切割函数,但是C++里没有,搜了很久都没搜到解决办法,无奈来求助大家.
C#实现效果
string temString = "1,2,3,4,5";
string[] arr = temString.Split(",");
然后arr = {"1","2","3","4","5"};

求在C++中的实现办法,越简洁越好,最好带注释,C++新手请多多照顾,谢谢先.
...全文
160 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
2010-04-03
  • 打赏
  • 举报
回复
顶一楼~
mstlq 2010-04-03
  • 打赏
  • 举报
回复

#include <string>
#include <vector>
#include <iostream>
using namespace std;
int main(int argc, const char *argv[])
{
string data=".,11,2,2,.,33,44.55..6,77.,";
string sptr=",.";
vector<string> result;

//开始
size_t b=0,e=0;
for(; (e=data.find_first_of(sptr,b))!=string::npos; b=e+1)
if(e!=b) result.push_back(data.substr(b,e-b));
//收工

for(vector<string>::iterator iter=result.begin(); iter!=result.end();++iter)
cout<<*iter<<endl;
system("pause");
return 0;
}
柯本 2010-04-03
  • 打赏
  • 举报
回复
string temString = "1,2,3,4,5";
string arr[5];
char *p = strtok((char *)temString.c_str(), ",");
int i=1;
if (p) arr[0]=p;
while(p = strtok(NULL, ","))
arr[i++]=p;
白云飘飘飘 2010-04-03
  • 打赏
  • 举报
回复
	string str="1,2,3,4,5";
stringstream ss(str);
vector<string> v;
string temp;

while(!ss.eof())
{
getline(ss,temp,',');
v.push_back(temp);
}

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧