您的位置:首页 > 编程语言 > C语言/C++

c++ 中的slipt实现

2016-05-24 20:51 337 查看
来自
http://www.cnblogs.com/dfcao/p/cpp-FAQ-split.html http://blog.diveinedu.com/%E4%B8%89%E7%A7%8D%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%88%86%E5%89%B2%E6%96%B9%E6%B3%95cc/
利用STL函数进行字符串分隔

涉及到string类中的的两个函数,find和substr

1,find函数(查找子字符串第一次出现的位置)

size_type find( const basic_string& str, size_type pos = 0 ) const;


str,表示目标字符串

pos,从pos位置开始

返回值:返回子串第一次出现的位置,否则返回string::npos尾后位置

2,substr函数(获得子字符串)

basic_string substr( size_type pos = 0,size_type count = npos );


pos,子字符串第一个字符的位置

count,子字符串中的长度,默认值为npos,npos就是 s的尾后位置

返回值是一个 字符串,即s [ pos, pos_count ),左闭右开。

在编程语言中,这个度:s.substr(pos, sizeof(sub) )

可以这么实现

class A{
void myslipt(string &s,vector<string> &re,string &c){
std::string::size_type pos1,pos2;
pos2 = s.find(c);///find
pos1 = 0;
while(std::string::npos != pos2){
re.push_back(s.substr(pos1,pos2-pos1));///[p1,p2)
pos1 = pos2+c.size();
pos2 = s.find(c,pos1);
}
if(pos1!=s.length()){
re.push_back(s.substr(pos1));
}
}

void test(ListNode *head){
cout<<"begin test...\n";
string str = "this is a string";
string c = "is";
vector<string> re;
myslipt(str,re,c);
for(auto i: re){
cout<<"|"<<i<<"|"<<endl;
}cout<<endl;

cout<<"end test...\n";
}
};


begin test...
|th|
| |
| a string|

end test...
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: