【发布时间】:2021-09-05 05:38:42
【问题描述】:
我有一个字符串“parrot -color green -peak”。我想将此字符串以
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main() {
// your code goes here
string s = "parrot -color green -peak";
char sep = '-';
map<string, string> clArgs;
// find first '-' and copy contents
string executable_name = s.substr(0, s.find_first_of(sep));
cout << "exec name = " << executable_name << endl;
s.erase(0, s.find_first_of(sep));
cout << "s = " << s << endl;
// iterate over string and copy key-value pairs
int pos;
while ((pos = s.find_first_of(sep, 1)) != string::npos)
{
string keyVal = s.substr(0, pos);
s = s.substr(pos);
string key, value;
key = keyVal.substr(0, keyVal.find_first_of(' '));
keyVal = keyVal.substr(keyVal.find_first_of(' ')+1);
value = keyVal.substr(0, keyVal.find_first_of(' '));
clArgs[key] = value;
}
if (s.length() != 0)
{
// there is still last command line arg remaining
// need to process it as well
clArgs[s.substr(0, s.find_first_of(' '))] = s.substr(s.find_first_of(' ')+1);
}
cout << "Printing key-value pairs ...\n";
for (map<string, string>::iterator it = clArgs.begin(); it != clArgs.end(); it++)
{
cout << "(key = " << it->first << ", value = " << it->second << ")\n";
}
return 0;
}
output from above code:-
exec name = parrot
s = -color green -peak
Printing key-value pairs ...
(key = -color, value = green)
(key = -peak, value = -peak)
expected output:-
exec name = parrot
s = -color green -peak
Printing key-value pairs ...
(key = -color, value = green)
(key = -peak, value = )
【问题讨论】:
-
命令行解析器实现应该比您实现的更复杂一些。现在,您没有任何指示应该或不应该有哪些命令有参数。
-peak是否有可能具有价值?如果需要一个值,那么这应该是一个错误——您不应该为尝试存储空白字符串而增加负担。 -
检查
find_first_ofs 是否真的找到任何东西是个好主意。 -
@PaulMcKenzie 我们不一定应该有价值观。在这个例子中 -peak
-
@molbdnilo 感谢您的建议。生病试一试:)
-
您应该尝试使您的命令行解析器以其他解析器的工作方式运行。你应该已经设置了一个
struct来描述每个命令的特征,即命令的名称,命令是否必须有参数等。然后创建一个数组,映射,无论什么,结构。然后解析每个-标记,将其与结构匹配以查看命令是否必须有参数。然后,您为获取参数而编写的代码开始发挥作用。现在,您假设每个命令都有一个参数,这显然是不正确的。
标签: c++ string algorithm stl unordered-map