首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C++ 字串分割:以分號為分隔符提取子串

     編輯:程式設計綜合問答

需求

str = "abc@163.com;def@163.com;ghi@163.com;",每次迴圈提取一段,遇到分號停止。

標準庫方案:string::find + substr

string str = "abc@163.com;def@163.com;ghi@163.com;";
size_t begin = 0, end = 0;
while ((end = str.find(';', begin)) != string::npos) {
    string token = str.substr(begin, end - begin);
    cout << token << endl; // 處理 token
    begin = end + 1;
}
// 處理最後一段(若無結尾分號)
if (begin < str.length()) {
    cout << str.substr(begin) << endl;
}

C++17 更簡潔:string_view + split (需第三方/手寫)


// 手寫 split 返回 vector 零拷貝
vector split(string_view s, char delim) {
    vector res;
    size_t pos = 0;
    while (pos < s.size()) {
        size_t next = s.find(delim, pos);
        res.emplace_back(s.substr(pos, next - pos));
        if (next == string_view::npos) break;
        pos = next + 1;
    }
    return res;
}

Boost 方案(專案已引入 Boost)

#include <boost/algorithm/string.hpp>
vector tokens;
boost::split(tokens, str, boost::is_any_of(";"), boost::token_compress_off);

關鍵點

  • find 返回 npos 表示未找到,迴圈終止條件。
  • substr(pos, len) 不修改原字串,安全高效。
  • 處理結尾分號導致的空 token(token_compress_off 保留空串)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved