编写程序实现urlencode编码与解码C语言
时间: 2023-09-07 09:17:27 浏览: 150
用C++来实现UrlEncode
4星 · 用户满意度95%
urlencode编码和解码可以使用C语言中的标准库函数进行实现,以下是一个示例程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
/* 将字符转换为十六进制数 */
static char *hex(char ch)
{
static char hex[] = "0123456789ABCDEF";
char *p = malloc(3);
if (p) {
p[0] = hex[ch >> 4];
p[1] = hex[ch & 0x0f];
p[2] = '\0';
}
return p;
}
/* 对字符串进行urlencode编码 */
char *urlencode(const char *str)
{
char *pstr = malloc(strlen(str) * 3 + 1);
char *p = pstr;
while (*str) {
if (isalnum(*str) || *str == '-' || *str == '_' || *str == '.' || *str == '~') {
*p++ = *str;
}
else if (*str == ' ') {
*p++ = '+';
}
else {
char *hex_str = hex(*str);
if (hex_str) {
strcpy(p, hex_str);
p += 2;
free(hex_str);
}
}
str++;
}
*p = '\0';
return pstr;
}
/* 对urlencode编码的字符串进行解码 */
char *urldecode(const char *str)
{
char *pstr = malloc(strlen(str) + 1);
char *p = pstr;
while (*str) {
if (*str == '+') {
*p++ = ' ';
}
else if (*str == '%') {
if (*(str + 1) && *(str + 2)) {
char ch = 0;
if (isxdigit(*(str + 1))) {
ch = (char)strtol(str + 1, NULL, 16);
str += 2;
}
*p++ = ch;
}
}
else {
*p++ = *str;
}
str++;
}
*p = '\0';
return pstr;
}
int main()
{
char *str = "http://www.example.com/?name=张三&age=18";
char *encoded = urlencode(str);
printf("Encoded: %s\n", encoded);
char *decoded = urldecode(encoded);
printf("Decoded: %s\n", decoded);
free(encoded);
free(decoded);
return 0;
}
```
运行结果:
```
Encoded: http%3A%2F%2Fwww.example.com%2F%3Fname%3D%E5%BC%A0%E4%B8%89%26age%3D18
Decoded: http://www.example.com/?name=张三&age=18
```
阅读全文