
将key和value存在map中,key为包含object名的完整路径,用nowdir存当前是在哪个object里,进入一个object,nowdir+object,出一个object,将nowdir中最后一个.之后的字符去除。
#include<iostream>
#include<string>
#include<map>
using namespace std;
map<string, string> t;
string fuc(int& i,string t) {//传入的i指向第一个引号
string text="";
i++;
while (t[i]!='"')
{
if (t[i] == '\\') {
i++;
text += t[i];
i++;
}
else {
text += t[i];
i++;
}
}
i++;//++后指向后一个引号的下一个字符
return text;
}
int main() {
int n, m;
string nowdir="";
string text;
cin >> n >> m;
getchar();//吃回车
for (int i = 0; i < n; i++) {
string temp;
getline(cin, temp);//getline传给string不含回车,含空格
text += temp;
}
text[0] = ' ';//去除最前和最后的大括号
text[text.length() - 1] = ' ';
int i = 1;
while (i<text.length()-1)
{
string key, value;
if (text[i] == ','||text[i]==' ') i++;//不管逗号和空格
else if (text[i] == '"') {//开始输入key
key = fuc(i, text);//返回时i为"下一个字符
while (text[i] == ' ') i++;
if (text[i] == ':')i++;//不管:
while (text[i] == ' ') i++;//不管空格
if (text[i] == '"') {//value为字符串
value = fuc(i, text);//此时i为,
t[nowdir + '.' + key] = value;
}
else if (text[i] == '{') {//value是object
i++;
value = "OBJECT";
nowdir = nowdir + '.' + key;//进入一个object更新nowdir
t[nowdir] = value;
}
}
else if (text[i] == '}') {
i++;
int dot= nowdir.rfind('.');
nowdir = nowdir.substr(0, dot);//把nowdir最后一个.之后的字符去除
}
}
for (int j = 0; j < m; j++) {
string c;
cin >> c;
c = '.' + c;
if (t.find(c) != t.end()) {
if (t[c] != "OBJECT") cout << "STRING " << t[c] << endl;
else cout << t[c] << endl;
}
else cout << "NOTEXIST" << endl;
}
}
该代码实现了一个解析器,用于处理包含键值对(key-valuepairs)和嵌套对象的字符串输入。它使用一个map来存储完整的路径作为key,对象或值作为value。当遇到对象时,路径会更新,退出对象时则会修剪路径。程序还提供了查询特定路径是否存在及其对应值的功能。
3803

被折叠的 条评论
为什么被折叠?



