#include #include #include // URLエンコード char* UrlEncode(const char* input) { const char* hex = "0123456789ABCDEF"; size_t len = strlen(input); char* encoded = (char*)malloc(len * 3 + 1); // 十分なメモリを確保 if (encoded) { size_t j = 0; for (size_t i = 0; i < len; ++i) { char ch = input[i]; if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch == '-' || ch == '_' || ch == '.' || ch == '~') { encoded[j++] = ch; } // URLエンコードにおいて特定の文字を16進数のエンコード形式に変換する else { // encoded の j 番目の位置に % を書き込んで、その後 j の値を 1 増やす encoded[j++] = '%'; // ch の上位4ビットに対応する16進数の文字を encoded 配列に格納し、 j の値を 1 増やす encoded[j++] = hex[(ch >> 4) & 0xF]; // ch の下位4ビットに対応する16進数の文字を取得して、それを encoded の j 番目の位置に格納し、j を 1 増やす encoded[j++] = hex[ch & 0xF]; } } encoded[j] = '\0'; // 終端を追加 } return encoded; } // URLデコード char* UrlDecode(const char* input) { size_t len = strlen(input); char* decoded = (char*)malloc(len + 1); // 十分なメモリを確保 if (decoded) { size_t j = 0; for (size_t i = 0; i < len; ++i) { // input の i 番目の文字が % であり、かつ i から始まる部分文字列が少なくとも 3 文字以上ある場合 if (input[i] == '%' && i + 2 < len) { char hex[3] = { input[i + 1], input[i + 2], '\0' }; // 文字列 hex を 16 進数表記されている整数に変換し、その結果を decodedChar に代入 int decodedChar = strtol(hex, NULL, 16); decoded[j++] = (char)decodedChar; i += 2; } // + を空白文字に置き換える else if (input[i] == '+') { decoded[j++] = ' '; } else { decoded[j++] = input[i]; } } decoded[j] = '\0'; // 終端を追加 } return decoded; } int main() { const char* originalUrl = "https://www.example.com/path with spaces/index.html?query=test query"; // URLエンコード char* encodedUrl = UrlEncode(originalUrl); if (encodedUrl) { printf("Encoded URL: %s\n", encodedUrl); // URLデコード char* decodedUrl = UrlDecode(encodedUrl); if (decodedUrl) { printf("Decoded URL: %s\n", decodedUrl); free(decodedUrl); } free(encodedUrl); } return 0; }