首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C++ 字串分割完整指南:標準庫手寫版與 Boost 單行版

     編輯:關於C語言

場景

依分隔字元將字串切割為子字串陣列/容器,是最基礎的文字處理需求。

方法一:標準庫手寫版(零相依)


#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 相容。

方法二:Boost.Algorithm 一行搞定


#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 壓縮連續分隔符

效能比較

C++23 預覽:零拷貝分割視圖


#include <string_view>
#include <ranges>
#include <iostream>

int main() {
    std::string s = "a,b,c";
    for (auto word : s | std::views::split(',')) {
        std::cout << std::string_view(word) << '\n';
    }
}

無分配、延遲評估、可直接搭配演算法,為現代 C++ 首選。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
方法相依速度記憶體功能豐富度
手寫 find/substr無最快最低基礎
std::stringstream無慢(串流開銷)高基礎
Boost.SplitBoost.Header-only快(內部優化)中極高
C++23 std::views::split標準庫極快(零拷貝視圖)最低中