MastRofDsastR MastRofDsastR - 8 months ago 64
C++ Question

C++ Split a string by blank spaces unless it is enclosed in quotes and store in a vector

I have a prompt that takes user input. I want to take this user input and store each word in a vector, splitting by a blank space, unless a group of words is contained between quotes, in which case I want all of the words within the quotes to count as 1.

For example, if the user enters the following:

12345 Hello World "This is a group"


Then I want the vector to store:

vector[0] = 12345
vector[1] = Hello
vector[3] = World
vector[4] = "This is a group"


I have the following code which splits the user input by blank space and stores it in a vector, but I am having trouble figuring out how make all text within quotes count as one.

string userInput

cout << "Enter a string: ";
getline(cin, userInput);

string buf;
stringstream ss(userInput);

vector<string> input;

while (ss >> buf){
input.push_back(buf);


I want to keep the quotes around the words where the quotes are entered by the user. I also want to save the results to a vector rather than just output the characters to the screen

Answer Source

Here is a working example:

#include <string>
#include <vector>
#include <iostream>
using namespace std;
int main(void) {
    string str = "12345 Hello World \"This is a group\"";
    vector<string> v;
    size_t i = 0, j = 0, begin = 0;
    while(i < str.size()) {
        if(str[i] == ' ' || i == 0) {
            if(i + 1 < str.size() && str[i + 1] == '\"') {
                j = begin + 1;
                while(j < str.size() && str[j++] != '\"');
                v.push_back(std::string(str, begin, j - 1 - i));
                begin = j - 1;
                i = j - 1;
                continue;
            }

            j = begin + 1;
            while(j < str.size() && str[j++] != ' ');
            v.push_back(std::string(str, begin, j - 1 - i - (i ? 1 : 0) ));
            begin = j;
        }
        ++i;
    }

    for(auto& str: v)
        cout << str << endl;
    return 0;
}

Output:

12345
Hello
World
"This is a group"

However, notice that this code is for demonstration, since it doesn't handle all cases. For example, if yuo have onle double quote in your input, then this while(j < str.size() && str[j++] != '\"'); will case the whole string from that point to not be splitted.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download