C++ UrlEncode UrlDecode

占位, 看到一个代码c++写的urlEncode和UrlDecode和写法,刚好用到, 好记性不如烂笔头啊

namespace Utility {
    std::string charToHex(unsigned char c) {
        short i = c;

        std::stringstream s;

        s << "%" << std::setw(2) << std::setfill('0') << std::hex << i;

        return s.str();
    }

    unsigned char hexToChar(const std::string &str) {
        short c = 0;

        if(!str.empty()) {
            std::istringstream in(str);

            in >> std::hex >> c;

            if(in.fail()) {
                throw std::runtime_error("stream decode failure");
            }
        }

        return static_cast<unsigned char>(c);
    }

    std::string urlEncode(const std::string &toEncode) {
        std::ostringstream out;

        for(std::string::size_type i = 0, len = toEncode.length(); i < len; ++i) {
            short t = toEncode.at(i);

            if(
                t == 45 ||          // hyphen
                (t >= 48 && t <= 57) ||       // 0-9
                (t >= 65 && t <= 90) ||       // A-Z
                t == 95 ||          // underscore
                (t >= 97 && t <= 122) ||  // a-z
                t == 126            // tilde
            ) {
                out << toEncode.at(i);
            } else {
                out << charToHex(toEncode.at(i));
            }
        }

        return out.str();
    }

    std::string urlDecode(const std::string &toDecode) {
        std::ostringstream out;

        for(std::string::size_type i = 0, len = toDecode.length(); i < len; ++i) {
            if(toDecode.at(i) == '%') {
                std::string str(toDecode.substr(i+1, 2));
                out << hexToChar(str);
                i += 2;
            } else {
                out << toDecode.at(i);
            }
        }

        return out.str();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值