You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将URL查询中的"+"解码为空格?Rust编码库使用求助

解决URL解码中+未替换为空格的问题

一、使用urlencoding库(推荐适配表单编码)

urlencoding 2.1.3的decode函数原生支持application/x-www-form-urlencoded格式解码,会自动把+替换为空格,同时解码%编码的字符。你的代码本身逻辑正确,运行后应该能得到目标结果:

fn main() {
    let result = urlencoding::decode("gmt_create=2024-05-05+11%3A14%3A19");
    // 解码后输出:gmt_create=2024-05-05 11:14:19
    print!("{}", result.unwrap_or_default().into_owned());
}

如果实际运行后+未被替换,检查依赖的urlencoding版本是否为2.1.3,或者传入的字符串是否存在格式异常。

二、使用percent-encoding库(需手动处理+)

percent-encoding库仅负责解码%编码的字符,默认不会处理表单编码中的+(因为+不属于通用percent编码范畴),需要手动补充替换逻辑,有两种实现方式:

方式1:解码前替换+

先把+替换为通用空格编码%20,再执行percent解码:

use percent_encoding::percent_decode_str;

fn main() {
    let encoded_str = "gmt_create=2024-05-05+11%3A14%3A19";
    let replaced_str = encoded_str.replace('+', "%20");
    let decoded_str = percent_decode_str(&replaced_str).decode_utf8().unwrap();
    println!("Decoded string: {}", decoded_str);
}

方式2:解码后替换+

先完成%编码解码,再把剩余的+替换为空格:

use percent_encoding::percent_decode_str;

fn main() {
    let encoded_str = "gmt_create=2024-05-05+11%3A14%3A19";
    let decoded_str = percent_decode_str(encoded_str).decode_utf8().unwrap();
    let final_str = decoded_str.replace('+', " ");
    println!("Decoded string: {}", final_str);
}

两种方式最终都能得到gmt_create=2024-05-05 11:14:19的结果。

内容的提问来源于stack exchange,提问作者Dolphin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 20:33:36