ccf 201709-3JSON查询

该代码实现了一个解析器,用于处理包含键值对(key-valuepairs)和嵌套对象的字符串输入。它使用一个map来存储完整的路径作为key,对象或值作为value。当遇到对象时,路径会更新,退出对象时则会修剪路径。程序还提供了查询特定路径是否存在及其对应值的功能。

将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;
    }

}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值