fork download
  1. /* src:urf-8 */
  2. #include <iostream>
  3. #include <sstream>
  4. #include <cctype>
  5.  
  6. std::string txUrlEncode(std::string &input_text) {
  7. std::stringstream work_ss;
  8. for (auto &ch : input_text)
  9. work_ss << '%' << std::hex << (int)(ch + 256) % 256;
  10. std::string output = work_ss.str();
  11. for (auto &c : output) c = (islower(c)) ? toupper(c) : c;
  12. return output;
  13. }
  14.  
  15. std::string txUrlDecode(std::string &input_text) {
  16. std::string out_text;
  17. for (auto p = input_text.begin(); p != input_text.end(); p++) {
  18. if (*p != '%') {
  19. out_text += *p;
  20. } else {
  21. p++;
  22. char c1 = (*p >= '0' && *p <= '9') ? *p - '0' : (*p >= 'A' && *p <= 'F') ? *p - 'A' + 10 : *p;
  23. c1 <<= 4;
  24. p++;
  25. char c2 = (*p >= '0' && *p <= '9') ? *p - '0' : (*p >= 'A' && *p <= 'F') ? *p - 'A' + 10 : *p;
  26. char c = c1 + c2;
  27. out_text += c;
  28. }
  29. }
  30. return out_text;
  31. }
  32.  
  33. int main() {
  34. std::string orgtext = "日 本";
  35. std::string encoded = txUrlEncode(orgtext);
  36. std::cout << "encoded: " << encoded << std::endl;
  37. std::string decoded = txUrlDecode(encoded);
  38. std::cout << "decoded: " << decoded << std::endl;
  39. return 0;
  40. }
  41. /* end */
  42.  
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
encoded: %E6%97%A5%20%E6%9C%AC
decoded: 日 本