如何将十六进制表示形式从URL(%)转换为std :: string(中文)?

问题描述 投票:0回答:1

简介

我有一些输入需要转换为正确的中文字符,但我认为我坚持将最终数字转换为字符串。我已经使用this hex to text converter online tool检查了e6b9af对应于文本

MWE

这里是我用来说明问题的最小示例。输入为"%e6%b9%af"(从其他地方的URL获得)。

#include <iostream>
#include <string>

std::string attempt(std::string path)
{
  std::size_t i = path.find("%");
  while (i != std::string::npos)
  {
    std::string sub = path.substr(i, 9);
    sub.erase(i + 6, 1);
    sub.erase(i + 3, 1);
    sub.erase(i, 1);
    std::size_t s = std::stoul(sub, nullptr, 16);
    path.replace(i, 9, std::to_string(s));
    i = path.find("%");
  }
  return path;
}

int main()
{
  std::string input = "%E6%B9%AF";
  std::string goal = "湯";

  // convert input to goal
  input = attempt(input);

  std::cout << goal << " and " << input << (input == goal ? " are the same" : " are not the same") << std::endl;

  return 0;
}

输出

湯 and 15120815 are not the same

预期输出

湯 and 湯 are the same

其他问题

是否所有外语字符都以3个字节表示,还是仅用于中文?由于我的尝试假设使用3个字节的块,因此这是一个好的假设吗?

c++ string hex
1个回答
0
投票

根据您的建议,并从this other post更改了示例。这就是我想出的。

#include <iostream>
#include <string>
#include <sstream>

std::string decode_url(const std::string& path)
{
  std::stringstream decoded;
  for (std::size_t i = 0; i < path.size(); i++)
  {
    if (path[i] != '%')
    {
      if (path[i] == '+')
        decoded << ' ';
      else
        decoded << path[i];
    }
    else
    {
      unsigned int j;
      sscanf(path.substr(i + 1, 2).c_str(), "%x", &j);
      decoded << static_cast<char>(j);
      i += 2;
    }
  }
  return decoded.str();
}

int main()
{
  std::string input = "%E6%B9%AF";
  std::string goal = "湯";

  // convert input to goal
  input = decode_url(input);

  std::cout << goal << " and " << input << (input == goal ? " are the same" : " are not the same") << std::endl;

  return 0;
}

输出

湯 and 湯 are the same

© www.soinside.com 2019 - 2024. All rights reserved.