c++ - 在地图的基础上存储字符串内容C++
问题描述
我有一个字符串“鹦鹉 -color green -peak”。我想将此字符串以 <key, value> 格式存储在地图中。其中第一个字符串被视为二进制可执行对象,其余值应以 map<key, value> 格式存储,其中(-string 表示键)下一个字符串被视为该特定键的值。如果值为空,则应存储为空字符串。但是从我的代码来看,它的存储键是值。还请检查从现有代码中观察到的预期输出和结果,以便更好地理解。提前致谢。
#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 = )
解决方案
- 如果参数字符串是可选的,那么我建议您将输入解析为令牌,然后逐个令牌处理。
- 您当前假设键/值对的值始终存在。搜索空格字符后不检查值是否存在。
推荐阅读
- css - 在 CSS 文件中访问 Laravel 的公共文件夹
- java - 在spring(boot)启动时扫描使用自定义@Annotation注释的任意目标(TYPE,METHOD,FIELD)
- javascript - Google Visualization API 在同一个 HTML 上加载 2 个脚本
- automation - 如何仅将 pdf 的特定页面内容复制到剪贴板?
- javascript - 文件(图像)不存储到本地存储
- javascript - 如何使用 javascript 或 jquery 等下载图像
- elasticsearch - 如何在elasticsearch脚本中将字段与_id进行比较?
- ruby-on-rails - 如果条件通过,则运行一个块
- javascript - 如何使用 JavaScript 访问特定的 json 元素
- c - 从 void 双指针数组输出 void 指针