首页 > 解决方案 > 如何在 C++ 中解析逗号分隔的字符串,其中一些元素用逗号引用?

问题描述

我有一个逗号分隔的字符串,我想将它存储在字符串向量中。字符串和向量是:

string s = "1, 10, 'abc', 'test, 1'";
vector<string> v;

理想情况下,我希望在没有单引号的情况下存储字符串 'abc' 和 'test, 1',如下所示,但我可以使用单引号来存储它们:

v[0] = "1";
v[1] = "10";
v[2] = "abc";
v[3] = "test, 1";

标签: c++stringcsvc++11

解决方案


您需要在这里做的是让自己成为一个解析器,可以按照您的意愿进行解析。这里我为你做了一个解析函数:

#include <string>
#include <vector>
using namespace std;

vector<string> parse_string(string master) {
    char temp; //the current character
    bool encountered = false; //for checking if there is a single quote
    string curr_parse; //the current string
    vector<string>result; //the return vector

    for (int i = 0; i < master.size(); ++i) { //while still in the string
        temp = master[i]; //current character
        switch (temp) { //switch depending on the character

        case '\'': //if the character is a single quote
            
            if (encountered) encountered = false; //if we already found a single quote, reset encountered
            else encountered = true; //if we haven't found a single quote, set encountered to true
            [[fallthrough]];

        case ',': //if it is a comma

            if (!encountered) { //if we have not found a single quote
                result.push_back(curr_parse); //put our current string into our vector

                curr_parse = ""; //reset the current string
                break; //go to next character
            }//if we did find a single quote, go to the default, and push_back the comma
            [[fallthrough]];

        default: //if it is a normal character
            if (encountered && isspace(temp)) curr_parse.push_back(temp); //if we have found a single quote put the whitespace, we don't care
            else if (isspace(temp)) break; //if we haven't found a single quote, trash the  whitespace and go to the next character
            else if (temp == '\'') break; //if the current character is a single quote, trash it and go to the next character.
            else curr_parse.push_back(temp); //if all of the above failed, put the character into the current string
            break; //go to the next character
        }
    }
    for (int i = 0; i < result.size(); ++i) { 
        if (result[i] == "") result.erase(result.begin() + i);  
        //check that there are no empty strings in the vector
        //if there are, delete them
    }
    return result;
}

这会根据需要解析您的字符串,并返回一个向量。然后,您可以在程序中使用它:

#include <iostream>
int main() {
    string s = "1, 10, 'abc', 'test, 1'";
    vector<string> v = parse_string(s);

    for (int i = 0; i < v.size(); ++i) {
        cout << v[i] << endl;
    }
}

并正确打印出:

1
10
abc
test, 1

推荐阅读