题解 | #参数解析#
参数解析
https://www.nowcoder.com/practice/668603dc307e4ef4bb07bcd0615ea677
#include <array> #include <cstddef> #include <iostream> #include <list> using namespace std; size_t findNoSpace(const string& str, size_t index) { size_t len = str.length(); for (int i = index; i < len; i++) { if (str.at(i) != ' ') { return i; } } return string::npos; } size_t rfindNoSpace(const string& str, size_t index) { for (int i = index; i >= 0; i--) { if (str.at(i) != ' ') { return i; } } return string::npos; } int main() { array<char, 1024> strSource = {0}; while (cin.getline(strSource.begin(), 1024)) { string str(strSource.begin()); size_t lastNoSpace = findNoSpace(str, 0); if (lastNoSpace == string::npos) { cout << 1 << endl << str << endl; return 0; } size_t lastQuota = 0; bool flag = false; list<string> res; size_t len = str.length(); for (int i = lastNoSpace; i < len; i++) { if (flag) { if (str.at(i) == '\"') { flag = false; size_t thisQuota = rfindNoSpace(str, i); res.push_back(str.substr(lastQuota, thisQuota - lastQuota)); lastNoSpace = findNoSpace(str, i + 1); i = lastNoSpace - 1; } } else { if (str.at(i) == '\"') { flag = true; lastQuota = findNoSpace(str, i + 1); } else if (str.at(i) == ' ') { res.push_back(str.substr(lastNoSpace, i - lastNoSpace)); lastNoSpace = findNoSpace(str, i + 1); } } } size_t thisNoSpace = rfindNoSpace(str, len - 1); if (lastNoSpace <= thisNoSpace) { string temp = str.substr(lastNoSpace, thisNoSpace - lastNoSpace + 1); res.push_back(temp); } cout << res.size() << endl; for (const auto & s : res) { cout << s << endl; } } return 0; }