HOWTO · C++
如何在 C++ 中拆分逗號分隔的字串
使用 std::stringstream 和 std::getline,或使用 std::string::find 和 std::string::substr,在 C++ 中拆分簡單的逗號分隔字串。
本頁內容
對於簡單的逗號分隔字串,std::stringstream 結合 std::getline 是將每個值收集到 std::vector<std::string> 中的一種直接方法。如果您需要控制每個片段的提取方式,std::string::find 和 std::string::substr 提供了手動替代方案。這些方法按分隔符拆分;它們不解析完整的 CSV 語法,例如帶引號欄位內部的逗號。
使用 std::stringstream 和 std::getline 拆分逗號分隔的字串
包含 <sstream> 以從輸入字串建構串流,並包含 <vector> 以儲存各個片段。將逗號作為第三個參數傳遞給 std::getline;每次呼叫都會讀取到該分隔符為止,並將提取的文字放入 item 中。迴圈將每個條目新增到向量中,然後列印收集到的值。
當後續程式碼需要對標記進行索引或再次迭代它們時,請使用 std::vector<std::string>;它會按輸入順序將每個提取的值儲存為單獨的字串。
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
int main() {
const std::string input = "apple,banana,cherry,dates";
std::stringstream stream(input);
std::vector<std::string> items;
std::string item;
while (std::getline(stream, item, ',')) {
items.push_back(item);
}
for (const std::string& value : items) {
std::cout << value << '\n';
}
}
apple
banana
cherry
dates
此範例使用逗號作為分隔符,並按順序儲存提取的四個字串。帶分隔符的 std::getline 可以在連續的逗號之間產生一個空條目,而位於末尾的分隔符在此迴圈中不會產生最終條目。如果您的輸入需要對這類情況進行不同的處理,請確定每個分隔符位置應表示什麼含義,並在解析邏輯中將其考慮在內。提取的字串會保留屬於輸入的任何空格,因此如果應捨棄周圍的空白,請分別修剪每個條目。當來源使用另一個單一字元(例如分號)時,請變更分隔符參數。
使用 std::string::find 和 std::string::substr 拆分逗號分隔的字串
std::string::find 成員定位下一個逗號,std::string::substr 複製其前面的字元。保留指向原始輸入的起始索引,而不是在處理過程中清除字元。當 find 傳回 std::string::npos 時,表示沒有更多的逗號,因此將剩餘的後綴作為最終條目並停止。
#include <iostream>
#include <string>
#include <vector>
int main() {
const std::string input = "apple,banana,cherry,dates";
std::vector<std::string> items;
std::string::size_type start = 0;
while (true) {
const std::string::size_type comma = input.find(',', start);
if (comma == std::string::npos) {
items.push_back(input.substr(start));
break;
}
items.push_back(input.substr(start, comma - start));
start = comma + 1;
}
for (const std::string& value : items) {
std::cout << value << '\n';
}
}
apple
banana
cherry
dates
最後的 substr(start) 呼叫很重要:它新增最後一個逗號之後的文字,包括沒有更多分隔符時的最後一個值。此版本還會將帶有尾隨逗號的輸入視為具有最終的空條目,這與上面的串流迴圈不同。對於完全為空的輸入,它同樣會儲存一個空字串,因此如果您的應用程式應將該輸入視為無值,請調整迴圈條件。搜尋從每個逗號後的字元開始,這樣可以避免在解析時變更輸入,並便於保留原始字串以備後用。這兩種方法都不處理帶引號的逗號或逸出引號;當這些規則屬於輸入格式的一部分時,請使用 CSV 解析器。