Created
August 21, 2023 03:01
-
-
Save daiakushi/17f438d94db9f75787cd3af7ad29ae94 to your computer and use it in GitHub Desktop.
Simple Command Parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string> | |
#include <vector> | |
#include <unordered_map> | |
using namespace std; | |
/* | |
* @ A simple parser can recognize shell command options in format | |
* "--<option> <args>" or "--<option>=<args>". | |
* @ Note. It tolerate spaces in args. | |
* e.g. | |
* > CmdParser.exe --abc 123 456 --def=789 012 | |
* param : abc, value : 123 456 | |
* param : def, value : 789 012 | |
*/ | |
unordered_map<string, string> Parse(const vector<string>& cmds) { | |
unordered_map<string, string> options; // (name, value) | |
for (int i = 0; i < cmds.size(); i++) { | |
string name, value; | |
if (cmds[i].substr(0, 2) == "--") { | |
auto equal = cmds[i].find('='); | |
if (equal != string::npos) { | |
name = cmds[i].substr(2, equal - 2); // "--" => 2 | |
value = cmds[i].substr(equal + 1) + " "; // "=" => 1 | |
} else { | |
name = cmds[i].substr(2); | |
value = ""; | |
} | |
while (i + 1 < cmds.size() && cmds[i + 1].substr(0, 2) != "--") { | |
value += cmds[i + 1] + " "; | |
i++; | |
} | |
if (!value.empty() && value.back() == ' ') value.pop_back(); | |
options[name] = value; | |
} | |
} | |
return options; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment