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

C++中如何split字符串

2015-10-10 09:22 232 查看
   
毫无疑问,split应该是任何非反人类的标准库编写者都应该提供的功能,因为实在是太常用了。但是不幸的是C++中的string并未提供此功能。诚然实现此功能不难,但为何老是要程序员重复造轮子?

   
好在boost里提供了几种split字符串的方式。

1)使用boost::split。注意is_any_of的意思是集合中的任何一个,而不是equals的意思,那如何根据字符串split原字符串?请看2和3。

#include <iostream>

#include <vector>

#include <string>

#include
<boost/algorithm/string.hpp>

using namespace std;

int main()

{

    string str(
"dfa&fda|dfdf");

   
vector<string> tokens;

   
boost::split(tokens, str,
boost::is_any_of("&|"));   

    for (size_t
i = 0; i < tokens.size(); ++ i)

    {

   
    cout
<< tokens[i]
<< endl;

    }

    return
0;

}

2) 使用boost::tokenize,注意
boost::char_separator<char>分隔符一样是集合的概念!但划分方法和boost::split不大一样,详看boost文档。

#include <iostream>

#include <vector>

#include <string>

#include <boost/tokenizer.hpp>

using namespace std;

int main()

{

    string
str("dfa||fda||dfdf");

   
vector<string> tokens;

   
boost::char_separator<char>
sep("|");

   
boost::tokenizer<boost::char_separator<char>
> tok(str, sep);

   
tokens.clear();

   
std::copy(tok.begin(), tok.end(),
std::back_inserter(tokens));   

    for (size_t
i = 0; i < tokens.size(); ++ i)

    {

   
    cout
<< tokens[i]
<< endl;

    }

    return
0;

}

3)使用boost::regex

#include <iostream>

#include <vector>

#include <string>

#include <boost/regex.hpp>

using namespace std;

int main()

{

    string
str("dfa||fda||dfdf");

   
vector<string> tokens;

    boost::regex
reg("\\|\\|");

   
boost::sregex_token_iterator it(str.begin(), str.end(), reg,
-1);

   
boost::sregex_token_iterator end;

    while
(it!=end)

    {

   
   
tokens.push_back(*it++);

    }

    for (size_t
i = 0; i < tokens.size(); ++ i)

    {

   
    cout
<< tokens[i]
<< endl;

    }

    return
0;

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