首先给出原题地址:
https://www.nowcoder.com/practice/668603dc307e4ef4bb07bcd0615ea677?tpId
以下是代码解析:
1 #include<iostream> 2 #include<vector> 3 #include<string> 4 using namespace std; 5 6 int main(){ 7 string str,stt; 8 int i=0; 9 bool flag = 0; 10 vector<string> arr; 11 while (getline(cin, str)){ 12 for (int i = 0; i < str.size(); ++i){ 13 if (str[i] == '"'){ 14 flag = ~flag; 15 } 16 else{ 17 if (str[i] == ' ' && flag==0){ 18 arr.push_back(stt); 19 stt = ""; 20 } 21 else{ 22 if (str[i]!='"') 23 stt += str[i]; 24 } 25 } 26 } 27 arr.push_back(stt); 28 cout << arr.size() << endl; 29 for (int i = 0; i < arr.size(); i++){ 30 cout << arr[i] << endl; 31 } 32 } 33 return 0; 34 }
重点是要意识到利用flag来区分处理在“ ”内外的字符