一、基本介紹
boost::split是一個用於將字符串按照給定的分割符進行分割的函數。在C++中,字符串分割是一個經常會用到的操作。boost::split幫助我們實現了這個功能,並且通過其提供的多種重載函數,我們可以靈活地適應不同的情況。
二、函數原型
template<typename SequenceT, typename RangeT>
void split(SequenceT &OutputSequence,
const RangeT &InputRange,
const RangeT &SeparatorRange,
token_compress_mode_type eCompress = token_compress_off);
其中,SequenceT是用於保存分割後的子字符串的容器,可以是std::vector, std::list, std::set等等;InputRange是原始字符串的範圍,可以是std::string或std::wstring類型;SeparatorRange是分割符的範圍,也可以是std::string或std::wstring類型;eCompress是一個可選參數,用於指定是否壓縮多餘的分隔符,默認不壓縮。
三、使用示例
下面介紹boost::split的使用方法。
1、將字符串分割成vector
#include <boost/algorithm/string.hpp>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
using namespace boost::algorithm;
int main()
{
string str = "boost::split is a very useful function.";
vector<string> vec;
split(vec, str, boost::is_any_of(" "));
for (auto s : vec)
cout << s << endl;
return 0;
}
運行結果:
boost::split
is
a
very
useful
function.
上面的代碼中,我們以空格為分隔符將一個字符串分割成了一個vector,利用循環輸出了所有子字符串。可以看到,分割函數並不會改變原始字符串。這裡使用了is_any_of()函數用於指定多個分隔符。
2、將字符串分割成set
#include <boost/algorithm/string.hpp>
#include <iostream>
#include <string>
#include <set>
using namespace std;
using namespace boost::algorithm;
int main()
{
string str = "alpha beta delta gamma beta gamma";
set<string> strSet;
split(strSet, str, boost::is_any_of(" "));
for (auto s : strSet)
cout << s << endl;
return 0;
}
運行結果:
alpha
beta
delta
gamma
上述代碼將原始字符串分割成了一個set,輸出了所有的子字符串。set無法存儲重複元素,因此在輸出時只顯示了一個beta和一個gamma。
3、對於連續出現的分隔符只保留一個
#include <boost/algorithm/string.hpp>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
using namespace boost::algorithm;
int main()
{
string str = "a |||| b ||| c ||| d|||| e";
vector<string> vec;
split(vec, str, boost::is_any_of("|"), token_compress_on);
for (auto s : vec)
cout << s << endl;
return 0;
}
運行結果:
a
b
c
d
e
上述代碼中,將原始字符串分割成了一個vector,用於顯示所有的子字符串。如果將token_compress_on改為token_compress_off,則會輸出多餘的空字符串。
四、總結
boost::split是一個用於將字符串分割成各個子字符串的C++函數模板。可以使用它將一個字符串以指定的分隔符分割成多個子字符串,並將這些子字符串存儲到一個容器中。這篇文章從函數原型、使用方法和示例三個方面講解了該函數模板的基本使用方法。
原創文章,作者:MOVSV,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/324522.html