c 语言 url 解码
问题:如何用 C 语言解码 URL 编码的字符串?
详细解答:
URL 编码是一种将特定字符转换为其 ASCII 代码的格式,以便通过网络安全传输。要解码 URL 编码的字符串,可以使用以下步骤:
- 分配内存:为解码后的字符串分配足够的内存空间。
- 逐个字符遍历:遍历 URL 编码的字符串,逐个字符处理。
- 检查字符:对于每个字符,检查它是否为百分号 (%)。
- 解码百分号编码:如果是百分号,则提取后面的两个字符并将其转换为十六进制数字。
- 还原字符:将十六进制数字转换为 ASCII 字符,并将其添加到解码后的字符串中。
- 忽略非 URL 编码的字符:对于非 URL 编码的字符(例如字母、数字和下划线),直接将其添加到解码后的字符串中。
- 终止字符串:解码完成后,用 '0' 结尾符终止解码后的字符串。
示例代码:
#include <stdio.h>
#include <stdlib.h>
char *url_decode(char *encoded_string) {
char *decoded_string;
int decoded_length = 0;
for (int i = 0; encoded_string[i] != '0'; i++) {
if (encoded_string[i] == '%') {
char hex_di<a style="color:#f60; text-decoration:underline;" href="https://www.php.cn/zt/15841.html" target="_blank">git</a>s[3] = { encoded_string[i+1], encoded_string[i+2], '0' };
int hex_value = strtol(hex_digits, NULL, 16);
decoded_string[decoded_length++] = hex_value;
i += 2;
} else {
decoded_string[decoded_length++] = encoded_string[i];
}
}
decoded_string[decoded_length] = '0';
return decoded_string;
}
int main() {
char encoded_string[] = "%20This%20is%20a%20URL%20encoded%20string";
char *decoded_string = url_decode(encoded_string);
printf("Decoded string: %sn", decoded_string);
free(decoded_string);
return 0;
}</stdlib.h></stdio.h>