c++解析自定义格式字符串

来源:互联网 发布:php工作流引擎原理 编辑:程序博客网 时间:2024/06/11 11:39

最近在开发功能模块时,需要支持自定义格式化字符串,便自己写了一个(效率不高,还请见谅)

直接上代码:

//自定义数据struct DescribeInfo{string desc;int type;int color;int size;int parm;void reset(){type = 1;desc = "";color = 1;size = 22;parm = 0;}};//根据分隔符切割字符串std::vector<string> getSubStrings(const string &str, char seperater){std::vector<string> strVec;string str1;auto it = str.begin();while (it != str.end()){if(*it != seperater){str1.push_back(*it);}else{strVec.push_back(str1);str1.clear();}++ it;}if(str1.length() != 0){strVec.push_back(str1);}return strVec;}std::string getValueByKey(const vector<std::string> &vec,const std::string &key){for (auto aa : vec){if (aa.find(key) != std::string::npos) {auto pos = aa.find_first_of('=');auto value = aa.substr(pos + 1, aa.size() - pos);return value;}}return "";}vector<DescribeInfo> analyzeDecColor(const string &str){string endStr = "end";int err = -1;vector<DescribeInfo> infoVec;///midint len = str.size();DescribeInfo info;info.reset();int pos1 = err, pos2 = err;for (int i = 0; i<len; ++i) {char c = str.at(i);if (c=='{'){pos1 = i;}else if (c=='}'){if (pos1>pos2){//cut last pos2 to last pos1int start = pos2;if (start != err){start += 1;//from '{' next pos} else{start = 0;}auto dis = pos1 - start;if (dis>0){info.desc = str.substr(start, dis);infoVec.push_back(info);}}if (i>pos1){if (pos2<pos1){auto formatStr = str.substr(pos1 + 1, i-pos1-1);if (formatStr != endStr){info.reset();auto strVec = getSubStrings(formatStr, ',');auto colorStr = getValueByKey(strVec, "color");auto typeStr = getValueByKey(strVec, "type");auto sizeStr = getValueByKey(strVec, "size");auto parmStr = getValueByKey(strVec, "parm");if (!colorStr.empty()){info.color = atoi(colorStr.c_str());}if (!typeStr.empty()){info.type = atoi(typeStr.c_str());}if (!sizeStr.empty()){info.size = atoi(sizeStr.c_str());}if (!parmStr.empty()){info.parm = atoi(parmStr.c_str());}} else{info.reset();}} else{//is contentinfo.desc = str.substr(pos2+1, i - pos2);infoVec.push_back(info);}}pos2 = i;}}auto maxIndex = pos1>pos2?pos1:pos2;if (maxIndex < len){info.desc = str.substr(maxIndex, len - maxIndex);infoVec.push_back(info);}return infoVec;}int main(int argc, char* argv[]){std::string str = "{{{color=6}滚滚长江东逝水,{{{{{type=6}浪花淘尽英雄,{end}是非成败转头空,{size=18}青山依旧在,几度夕阳红}{}{";auto vec = analyzeDecColor(str);for (auto info:vec){std::cout << "type=" << info.type << "  color=" << info.color << "  size=" << info.size << "  desc=" << info.desc << std::endl;}getchar();return 0;}


测试结果:


原创粉丝点击