在python,c#等语言中,string都是默认提供split这个函数的,C++里面却没有默认实现,但又经常会用到,所以就简单实现了一个:
int SplitString(const string &srcStr,const string &splitStr,vector<string> &destVec)
{
if(srcStr.size()==0)
{
return 0;
}
size_t oldPos,newPos;
oldPos=0;
newPos=0;
string tempData;
while(1)
{
newPos=srcStr.find(splitStr,oldPos);
if(newPos!=string::npos)
{
tempData = srcStr.substr(oldPos,newPos-oldPos);
destVec.push_back(tempData);
oldPos=newPos+splitStr.size();
}
else if(oldPos<=srcStr.size())
{
tempData= srcStr.substr(oldPos);
destVec.push_back(tempData);
break;
}
else
{
break;
}
}
return 0;
}
简单使用代码如下:
string src = ",,w,,ai,,,nio,,";
string splitStr = ",,";
vector<string> destVec;
SplitString(src,splitStr,destVec);
for(vector<string>::iterator it = destVec.begin();it!=destVec.end();++it)
{
cout<<*it<<endl;
}
输出为:
w
ai
,nio
当然,一般split我们还是使用字符分割比较多。
另外也说一个问题,stl里面string的find和rfind方法是可以查找字符串的,但是find_last_of和find_first_of只能查找字符,即使传入的参数是字符串,查找的也是字符。
原创文章,版权所有。转载请注明:转载自Vimer的程序世界 [ http://www.vimer.cn ]
本文链接地址: http://www.vimer.cn/?p=1683
Posted in: C/C++ by Dante,7,663 views Tags: c++, cpp, split, stl, string
较旧一篇?0?0 关于mysql_free_result和mysql_close的解惑
在C++中实现foreach循环,比for_each更简洁!?0?3较新一篇
12 个评论 在 “一个简单的stl中string的split函数”
ww说道:
2010年10月21日11:21 下午
也可以考虑用下面这个:
strtok的介绍
功 能: 查找由在第二个串中指定的分界符分隔开的单词
用 法: char *strtok(char *str1, char *str2);
#include ;
#include ;
int main(void)
{
char input[16] = “abc,d”;
char *p;
strtok places a NULL terminator
in front of the token, if found
p = strtok(input, “,”);
if (p) printf(“%s\n”, p);
A second call to strtok using a NULL
as the first parameter returns a pointer
to the character following the token
p = strtok(NULL, “,”);
if (p) printf(“%s\n”, p);
return 0;
}
[回复]
Terrence 回复:
十月 22nd, 2010 at 10:44 上午
同意~
用strtok封装一个split会少写些代码,说不定速度还会快些。
[回复]
Dante 回复:
十月 22nd, 2010 at 4:32 下午
The strtok() function uses a static buffer while parsing, so it’s not thread safe. Use strtok_r() if this matters to you.
这是man里的说明哦,如果用strtok_r可能的确更快一些~
[回复]
ww 回复:
十月 24th, 2010 at 10:21 下午
汗一个, 刚知道man还有这个功能, 学习了
[回复]
hwywhywl说道:
2010年10月24日4:22 下午
请教下博主,vimscript中如何获得当前打开文件的文件类型。
[回复]
Dante 回复:
十月 24th, 2010 at 4:42 下午
&ft 就是。
可以执行一下
:echo &ft
试试。
[回复]
hwywhywl说道:
2010年10月24日5:04 下午
嗯,谢谢博主,看了博主那篇《Vim在源代码中自动添加作者信息》,对这篇的vimscript做了一下修改,支持对pyton文件得注释。
[回复]
Dante 回复:
十月 24th, 2010 at 7:42 下午
哈,举一反三,加油~
[回复]
熊猫说道:
2010年10月24日11:12 下午
支持博主!
[回复]
sw说道:
2010年11月11日12:15 下午
split代价有点大的说。所以C++不提供。另外split和正则配合才是最完美的。
[回复]
Dante 回复:
十一月 11th, 2010 at 10:49 下午
呃。。。即使效率低下,提供一个现成的也好呀。。。
[回复]
壮壮说道:
2012年03月19日5:13 下午
strsep 也不错 这边有实现的代码
http://www.koders.com/cpp/fid447A740B67AF498AF5C189E4BAA97F441567A25C.aspx
[回复]
我要评论
本文介绍了一种在 C++ 中手动实现 string 类型 split 函数的方法,并提供了示例代码,同时还讨论了使用标准库函数 strtok 和 strsep 的优缺点。
1216

被折叠的 条评论
为什么被折叠?



