C++,c++,string,algorithm,stl,unordered-map"/>

首页 > 解决方案 > 在地图的基础上存储字符串内容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 = )

标签: c++stringalgorithmstlunordered-map

解决方案


  1. 如果参数字符串是可选的,那么我建议您将输入解析为令牌,然后逐个令牌处理。
  2. 您当前假设键/值对的值始终存在。搜索空格字符后不检查值是否存在。

推荐阅读