在 VC++ 開發中,標準庫未提供現成的字串分割功能。本文提供一個基於 CString 與 CStringArray 的輕量級分割函數,支援自訂分隔字元,適用於解析「鍵=值;鍵=值;」格式的設定字串。
// 參數說明:
// source - 待分割的源字串
// dest - 儲存分割結果的字串陣列(輸出參數)
// division - 分隔字元(如 ';'、','、'|' 等)
void decodeCString(CString source, CStringArray& dest, char division);
dest.RemoveAll()void decodeCString(CString source, CStringArray& dest, char division) {
dest.RemoveAll();
for (int i = 0; i < source.GetLength(); i++) {
if (source.GetAt(i) == division) {
// 取得分隔符左側內容
dest.Add(source.Left(i));
// 移除已處理部分,保留右側待續處理
for (int j = 0; j < (dest.GetSize() - 1); j++) {
dest[dest.GetSize() - 1] =
dest[dest.GetSize() - 1].Right(
dest[dest.GetSize() - 1].GetLength() -
dest[j].GetLength() - 1);
}
}
}
}
CString cfg = _T("姓名=劉德華;年齡=40;國籍=中國;");
CStringArray fields;
decodeCString(cfg, fields, _T(';'));
// fields 內容:
// [0] = "姓名=劉德華"
// [1] = "年齡=40"
// [2] = "國籍=中國"
// [3] = "" (尾部分隔符產生空項,可視需求過濾)
CString::Tokenize() (VC7.1+) 或手寫單趟掃描std::string_view + std::search 實現零拷貝分割boost::algorithm::split() 提供豐富策略本函數雖簡單,但在舊版 VC6 專案維護或嵌入式環境無 STL 時,仍具備即拿即用的實用價值。