MFC/ATL 專案常需將字串依指定分隔符切割為子字串陣列。本文提供一個通用 Split 函式,支援任意長度分隔符、使用 CAtlArray<CString> 回傳結果,且不修改原字串。
void Split(const CString& content, const CString& pattern,
CAtlArray<CString>& strList)
{
int iPos = content.Find(pattern);
int iStart = 0;
while (iPos != -1) {
strList.Add(content.Mid(iStart, iPos - iStart));
iStart = iPos + pattern.GetLength();
iPos = content.Find(pattern, iStart);
}
// 最後一段
if (iStart <= content.GetLength()) {
strList.Add(content.Mid(iStart));
}
}
CAtlArray<CString> parts;
CString src = _T("apple,banana,orange,grape");
Split(src, _T(","), parts);
for (int i = 0; i < parts.GetCount(); ++i) {
TRACE(_T("Part %d: %s\n"), i, parts[i]);
}
// 輸出:
// Part 0: apple
// Part 1: banana
// Part 2: orange
// Part 3: grape
void SplitEx(const CString& content, const CString& pattern,
CAtlArray<CString>& strList, bool keepEmpty = false)
{
if (pattern.IsEmpty()) return; // 避免無限迴圈
int start = 0;
while (true) {
int pos = content.Find(pattern, start);
if (pos == -1) {
CString tail = content.Mid(start);
if (keepEmpty || !tail.IsEmpty()) strList.Add(tail);
break;
}
CString token = content.Mid(start, pos - start);
if (keepEmpty || !token.IsEmpty()) strList.Add(token);
start = pos + pattern.GetLength();
}
}
CAtlArray 為 ATL 輕量陣列,無 MFC 執行期相依,適合 DLL 介面。CStringA/std::string 並預先 reserve 容量。CString::Tokenize (MFC 8.0+) 更簡潔。