How to split a string on commas, ignoring the commas in quoted substrings with C++

2 Answers

0 votes
#include <iostream>
#include <vector>
#include <string>

std::vector<std::string> splitString(const std::string& s) {
    std::vector<std::string> result;
    std::string current;
    bool inQuotes = false;

    for (size_t i = 0; i < s.size(); ++i) {
        char ch = s[i];

        if (ch == '"') {
            // Toggle quote state
            inQuotes = !inQuotes;
            current += ch;
        }
        else if (ch == ',' && !inQuotes) {
            // Comma outside quotes → split here
            result.push_back(current);
            current.clear();
        }
        else {
            current += ch;
        }
    }

    // Add last field
    result.push_back(current);
    
    return result;
}

int main() {
    std::string input = R"(one,"two, with comma",three,"four, ""quoted"" five")";

    std::vector<std::string> fields = splitString(input);

    for (size_t i = 0; i < fields.size(); ++i) {
        std::cout << "Split " << i << ": [" << fields[i] << "]\n";
    }
}



/*
run:

Split 0: [one]
Split 1: ["two, with comma"]
Split 2: [three]
Split 3: ["four, ""quoted"" five"]

*/

 



answered May 7 by avibootz
edited May 7 by avibootz
0 votes
#include <iostream>
#include <vector>
#include <string>

std::vector<std::string> splitString(const std::string& s) {
    std::vector<std::string> result;
    std::string current;
    bool inQuotes = false;

    for (size_t i = 0; i < s.size(); ++i) {
        char c = s[i];

        if (c == '"') {
            // Check for doubled quotes ("")
            if (i + 1 < s.size() && s[i + 1] == '"') {
                current += '"';   // Add literal quote
                i++;              // Skip the second quote
            } else {
                inQuotes = !inQuotes;  // Toggle quote state
            }
        }
        else if (c == ',' && !inQuotes) {
            result.push_back(current);
            current.clear();
        }
        else {
            current += c;
        }
    }

    result.push_back(current);
    return result;
}

int main() {
    std::string input = "one,\"two, with comma\",three,\"four, with \"\"quotes\"\"\"";

    std::vector<std::string> fields = splitString(input);

    for (size_t i = 0; i < fields.size(); ++i) {
        std::cout << "Split " << i << ": [" << fields[i] << "]\n";
    }
}



/*
run:

Split 0: [one]
Split 1: [two, with comma]
Split 2: [three]
Split 3: [four, with "quotes"]

*/

 



answered May 7 by avibootz
...