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 解析器。