依分隔字元將字串切割為子字串陣列/容器,是最基礎的文字處理需求。
#include <string>
#include <vector>
void split(const std::string& s, char delim, std::vector<std::string>& out) {
size_t start = 0;
while (true) {
size_t pos = s.find(delim, start);
out.push_back(s.substr(start, pos - start));
if (pos == std::string::npos) break;
start = pos + 1;
}
}
// 泛型版本(支援 wstring 等)
template <typename CharT>
void split(const std::basic_string<CharT>& s, CharT delim,
std::vector<std::basic_string<CharT>>& out) {
typename std::basic_string<CharT>::size_type start = 0;
while (true) {
auto pos = s.find(delim, start);
out.push_back(s.substr(start, pos - start));
if (pos == std::basic_string<CharT>::npos) break;
start = pos + 1;
}
}
特點:保留空欄位(連續分隔符會產生空字串)、無額外分配、C++98 相容。
#include <boost/algorithm/string.hpp>
#include <string>
#include <vector>
#include <list>
#include <iostream>
int main() {
std::string s = "I|am|a|bad|boy";
std::vector<std::string> vec;
boost::split(vec, s, boost::is_any_of("|")); // 分隔符可為字串集合
for (auto& t : vec) std::cout << t << ' ';
// 輸出: I am a bad boy
// 直接存入 list、deque 等任意容器
std::list<std::string> lst;
boost::split(lst, s, boost::is_any_of("|"));
return 0;
}
進階用法:
boost::is_any_of(" ,\t"):多字元分隔符boost::is_equal("::"):固定字串分隔boost::algorithm::split_regex:正則分隔boost::algorithm::split 可選 token_compress_on 壓縮連續分隔符| 方法 | 相依 | 速度 | 記憶體 | 功能豐富度 |
|---|---|---|---|---|
手寫 find/substr | 無 | 最快 | 最低 | 基礎 |
std::stringstream | 無 | 慢(串流開銷) | 高 | 基礎 |
| Boost.Split | Boost.Header-only | 快(內部優化) | 中 | 極高 |
C++23 std::views::split | 標準庫 | 極快(零拷貝視圖) | 最低 | 中 |