In: Computer Science
C++
C++
We are prompting input from the users.
Users input "I like the book "The little prince" very much"
I want to separate this sentence by the order "I" "like" "the" "book" "the little prince" "very" "much". (Keep the quotation mark of little prince, because it is the way the user entered)
and adding this to a arraylist in c++
#include <iostream> #include <vector> using namespace std; vector<string> parseCSV(string s) { vector<string> result; // while string has a space while(s.find(" ") != string::npos) { int index = -1; bool insideQuote = false; for(int i=0; i<s.size(); i++) { if(s[i] == '"') { insideQuote = !insideQuote; } else if(s[i] == ' ') { if(!insideQuote) { index = i; break; } } } // break token from index. string token = s.substr(0, index); s = s.substr(index + 1); // remove space from start of token while(token != "" && token[0] == ' ') { token = token.substr(1); } if(token != "") { result.push_back(token); } } while(s != "" && s[0] == ' ') { s = s.substr(1); } if(s != "") { result.push_back(s); } return result; } int main() { string s = "I like the book \"The little prince\" very much"; vector<string> tokens = parseCSV(s); for(string t: tokens) { cout << t << endl; } }
************************************************** Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.
Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.