Boost库是C++的一个类扩展库,其中的tokenizer模块可以方便地将一个字符串分割成多个子串。本文将向大家介绍如何使用boost::tokenizer模块进行字符串分割,并提供相关的测试程序。
首先,在使用boost::tokenizer模块之前需要在代码中引入boost头文件:
#include <boost/tokenizer.hpp>
接着,我们可以定义一个字符串,然后将其根据指定的分隔符进行分割:
std::string str = "hello,world,boost";
boost::tokenizer<boost::char_separator<char>> tokens(str, boost::char_separator<char>(","));
for (const auto& token : tokens) {
std::cout << token << std::endl;
}
上述代码中,我们使用",“作为分隔符,将字符串"hello,world,boost"分割成了三个子串"hello”、“world"和"boost”,并通过for循环逐一输出。
除了使用字符作为分隔符,我们还可以使用正则表达式进行分割。例如,下面