文章详情
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