C语言实现URLDecoder功能
时间: 2024-05-02 11:17:57 浏览: 153
C语言实现URLDecoder功能可以使用以下代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* urldecode(const char*);
char hex2char(const char*);
int main() {
char url[] = "http%3A%2F%2Fwww.google.com%3Fq%3Dc%2B%2B";
char* decoded = urldecode(url);
printf("%s\n", decoded);
free(decoded);
return 0;
}
char* urldecode(const char* url) {
size_t len = strlen(url);
char* decoded = (char*)malloc(len + 1);
int j = 0;
for (int i = 0; i < len; i++) {
if (url[i] == '%') {
decoded[j++] = hex2char(&url[i+1]);
i += 2;
} else if (url[i] == '+') {
decoded[j++] = ' ';
} else {
decoded[j++] = url[i];
}
}
decoded[j] = '\0';
return decoded;
}
char hex2char(const char* hex) {
char ch = 0;
for (int i = 0; i < 2; i++) {
ch <<= 4;
if (hex[i] >= '0' && hex[i] <= '9') {
ch |= hex[i] - '0';
} else if (hex[i] >= 'a' && hex[i] <= 'f') {
ch |= hex[i] - 'a' + 10;
} else if (hex[i] >= 'A' && hex[i] <= 'F') {
ch |= hex[i] - 'A' + 10;
}
}
return ch;
}
```
上述代码中,urldecode函数将编码过的URL字符串url解码成普通的字符串,并返回解码后的字符串。hex2char函数将两个十六进制字符转换成一个字符。在main函数中,我们调用urldecode函数对URL进行解码,并打印出解码后的字符串。
阅读全文