|
C语言中实现URLEncode和URLDecode 在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编码字符串。记得在使用后释放分配的内存空间,以避免内存泄漏。
|
|
|