L o a d i n g . . .
主打一个C++
文章详情

C++中实现js方法encodeURIComponent与decodeURIComponent

Posted on 2025-01-02 06:35:58 by 主打一个C++

1. encodeURIComponent

    std::string encodeURIComponent(const std::string& value) {
        std::ostringstream encoded;
        for (unsigned char c : value) {
            if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
                encoded << c; // 直接添加
            }
            else {
                encoded << '%' << std::uppercase << std::hex << static_cast<int>(c); // 编码
            }
        }
        return encoded.str();
    }

2. decodeURIComponent

    std::string decodeURIComponent(const std::string& value) {
        std::string decoded;
        for (size_t i = 0; i < value.length(); ++i) {
            if (value[i] == '%') {
                if (i + 2 < value.length()) {
                    std::string hex = value.substr(i + 1, 2);
                    char c = static_cast<char>(std::stoi(hex, nullptr, 16));
                    decoded += c; // 解码
                    i += 2; // 跳过已处理的两个字符
                }
            }
            else if (value[i] == '+') {
                decoded += ' '; // 将加号替换为空格
            }
            else {
                decoded += value[i]; // 直接添加
            }
        }
        return decoded;
    }


*转载请注明出处:原文链接:https://cpp.vin/page/121.html

作者近期文章
提示
×
确定
数据库执行: 8次 总耗时: 0.01s
页面加载耗时: 



wechat +447752296473
wechat cpp-blog