文字列のエンコード・デコード
あと知り合いMがを16進数文字列を解読可能に直すプログラムを書いたのを見せてくれました。実験を選択した人にはずいぶん参考になる気がしたので掲載します。了解はとりました。
はやさんによれば、「%encode」というのが当たりらしい。
初心者てググる言葉をしらないから初心者なんだなと思う。
#include <iostream> #include <string> int hexToInt(char c) { if ('0' <= c && c <= '9') { return c - '0'; } else if ('a' <= c && c <= 'f') { return c - 'a' + 0x0a; } else if ('A' <= c && c <= 'F') { return c - 'A' + 0x0a; } else { return -1; } } char intToHex(int x) { if (0 <= x && x <= 9) { return x + '0'; } else if (10 <= x && x <= 15) { return x - 10 + 'A'; } else { return '\0'; } } void urlEncode(std::string& out, const std::string& str) { for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) { char c = *it; if (c == ' ') { out += '+'; } else if (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z') || ('0' <= c && c <= '9') || (c == '@') || (c == '*') || (c == '-') || (c == '.') || (c == '_')) { out += c; } else { out += '%'; out += intToHex((c >> 4) & 0x0f); out += intToHex(c & 0x0f); } } } void urlDecode(std::string& out, const std::string& str) { for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) { char c = *it; if (*it == '+') { out += ' '; } else if (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z') || ('0' <= c && c <= '9') || (c == '@') || (c == '*') || (c == '-') || (c == '.') || (c == '_')) { out += c; } else if (c == '%') { int a = 0; for (int i = 0; i < 2; ++i) { ++it; if (it == str.end()) { return; } int b = hexToInt(*it); if (b == -1) { return; } a = (a << 4) + b; } out += static_cast<char>(a); } else { return; } } } int main() { std::string str1 = "+ test desu yo. +"; std::cout << str1 << std::endl; std::string str2; urlEncode(str2, str1); std::cout << str2 << std::endl; std::string str3; urlDecode(str3, str2); std::cout << str3 << std::endl; return 0; }