C++字符串分割与解析代码学习

1 分钟阅读

源码链接

#include <iostream>
#include <map>
#include <string>
#include <vector>

/**
 * @brief           把字符串前后的字符串给去除
 * @param           s       [in]    要剪切的字符串
 * @param           chars   [in]    要去除什么的字符串
 * @return          std::string& 剪切后的字符串
 * @author          lijiancong(lijiancong@gbcom.com.cn)
 * @note
 */
static std::string& strip(std::string& s, const std::string& chars = " ") {
  s.erase(0, s.find_first_not_of(chars.c_str()));
  s.erase(s.find_last_not_of(chars.c_str()) + 1);
  return s;
}

/**
 * @brief           以特定符号为分隔符,切分字符串并放入vector里
 * @param           s           [in]    原字符串
 * @param           tokens      [out]   剪切后的子字符串
 * @param           delimiters  [in]    分隔符
 * @author          lijiancong(lijiancong@gbcom.com.cn)
 * @note
 */
static void split(const std::string& s, std::vector<std::string>& tokens,
                  const std::string& delimiters = " ") {
  std::string::size_type lastPos = s.find_first_not_of(delimiters, 0);
  std::string::size_type pos = s.find_first_of(delimiters, lastPos);
  while (std::string::npos != pos || std::string::npos != lastPos) {
    tokens.push_back(s.substr(lastPos, pos - lastPos));
    lastPos = s.find_first_not_of(delimiters, pos);
    pos = s.find_first_of(delimiters, lastPos);
  }
}

static void parse(std::string& s, std::map<std::string, std::string>& items) {
  std::vector<std::string> elements;
  s.erase(0, s.find_first_not_of(" {"));
  s.erase(s.find_last_not_of("} ") + 1);
  split(s, elements, ",");
  for (auto& iter : elements) {
    std::vector<std::string> kv;
    split(iter, kv, ":");
    if (kv.size() != 2) continue;
    items[strip(kv[0], " \"")] = strip(kv[1], " \"");
  }
}

int main() {
  std::string data =
      "  {  \"key1\"  :  \"data1\"  ,  \"key2\"  :  \"data2\"    }  ";
  std::map<std::string, std::string> items;
  parse(data, items);

  for (const auto& iter:items){
    std::cout << "key=" << iter.first << ",value=" << iter.second << std::endl;
  }
  system("pause");
}

标签:

分类:

更新时间: