fork download
  1. #ifdef _MSC_VER
  2. #define _SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING
  3. #endif
  4.  
  5. #include <cstddef>
  6. #include <cstdlib>
  7. #include <iostream>
  8. #include <string>
  9. #include <algorithm>
  10. #include <regex>
  11. #include <codecvt>
  12.  
  13. #ifdef _WIN32
  14. #if !defined(NOMINMAX)
  15. #define NOMINMAX
  16. #endif
  17. #if !defined(WIN32_LEAN_AND_MEAN)
  18. #define WIN32_LEAN_AND_MEAN
  19. #endif
  20. #include <Windows.h>
  21. #endif
  22.  
  23. auto main() -> int
  24. {
  25. #ifdef _WIN32
  26. SetConsoleOutputCP(CP_UTF8);
  27. #endif
  28.  
  29. std::string json_string = "Json mit dem UE [u]00fc, dem AE [u]00e4 und der Kuh [u]1f42e ;-)";
  30.  
  31. std::regex unicode_regex("\\[u\\]([0-9abcdefABCDEF]{2,8})");
  32. std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> convert;
  33.  
  34. std::string utf8_string;
  35. std::size_t i = 0;
  36.  
  37. std::for_each(
  38. std::sregex_iterator{
  39. std::cbegin(json_string),
  40. std::cend(json_string),
  41. unicode_regex
  42. },
  43. std::sregex_iterator{},
  44. [&](std::smatch match){
  45. // JSON-String von letzter Position bis zum Match anhängen.
  46. utf8_string.append(json_string.substr(i, match.position() - i));
  47. // Submatch via strtoul in char32_t umwandeln, nach UTF-8
  48. // konvertieren und anhängen.
  49. utf8_string.append(
  50. convert.to_bytes(
  51. std::strtoul(match.str(1).c_str(), nullptr, 16)
  52. )
  53. );
  54. i = match.position() + match.length();
  55. }
  56. );
  57. // Rest des JSON-String anhängen.
  58. utf8_string.append(json_string.substr(i));
  59.  
  60. std::cout << json_string << std::endl;
  61. std::cout << utf8_string << std::endl;
  62. }
Success #stdin #stdout 0s 4196KB
stdin
Standard input is empty
stdout
Json mit dem UE [u]00fc, dem AE [u]00e4 und der Kuh [u]1f42e ;-)
Json mit dem UE ü, dem AE ä und der Kuh 🐮 ;-)