C语言中实现URLEncode和URLDecode

文章介绍了在C语言中使用`urlEncode`和`urlDecode`函数进行URL编码和解码的方法,以及如何处理特殊字符和内存管理。附带提及了在VC++中实现类似功能的资源。

在C语言中,你可以使用各种字符串操作函数来实现URL编码和解码。以下是在C中实现URL编码和解码的示例:

URL编码(URLEncode):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char* urlEncode(const char* str) {
    const char* hex = "0123456789ABCDEF";
    size_t len = strlen(str);
    char* encoded = malloc(3 * len + 1);  // 为编码后的字符串分配内存空间
     size_t j = 0;
    for (size_t i = 0; i < len; i++) {
        if (isalnum((unsigned char)str[i]) || str[i] == '-' || str[i] == '_' || str[i] == '.' || str[i] == '~') {
            encoded[j++] = str[i];
        } else if (str[i] == ' ') {
            encoded[j++] = '+';
        } else {
            encoded[j++] = '%';
            encoded[j++] = hex[(str[i] >> 4) & 0xF];
            encoded[j++] = hex[str[i] & 0xF];
        }
    }
    encoded[j] = '\0';  // 编码后的字符串以空字符结尾
    return encoded;
}
 int main() {
    const char* url = "Hello World!";
    char* encodedUrl = urlEncode(url);
    printf("编码后的URL:%s\n", encodedUrl);
    free(encodedUrl);  // 记得释放分配的内存空间
    return 0;
}

URL解码(URLDecode):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char* urlDecode(const char* str) {
    size_t len = strlen(str);
    char* decoded = malloc(len + 1);  // 为解码后的字符串分配内存空间
     size_t j = 0;
    for (size_t i = 0; i < len; i++) {
        if (str[i] == '+') {
            decoded[j++] = ' ';
        } else if (str[i] == '%') {
            if (isxdigit((unsigned char)str[i + 1]) && isxdigit((unsigned char)str[i + 2])) {
                char hex[3] = {str[i + 1], str[i + 2], '\0'};
                decoded[j++] = strtol(hex, NULL, 16);
                i += 2;
            } else {
                decoded[j++] = str[i];
            }
        } else {
            decoded[j++] = str[i];
        }
    }
    decoded[j] = '\0';  // 解码后的字符串以空字符结尾
    return decoded;
}
 int main() {
    const char* encodedUrl = "Hello%20World%21";
    char* decodedUrl = urlDecode(encodedUrl);
    printf("解码后的URL:%s\n", decodedUrl);
    free(decodedUrl);  // 记得释放分配的内存空间
    return 0;
}

这些示例演示了如何在C语言中执行URL编码和解码。 urlEncode 函数用于对给定的字符串进行编码,而 urlDecode 函数用于解码给定的URL编码字符串。记得在使用后释放分配的内存空间,以避免内存泄漏。

另外在VC++中实现上面的功能,可以看一下另一篇文章:

VC++中实现URLEncode和URLDecode

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

依星net188.com

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值