C++ 如何将十六进制表示从URL(%)转换为std::string(中文文本)? 简介

C++ 如何将十六进制表示从URL(%)转换为std::string(中文文本)? 简介,c++,string,hex,C++,String,Hex,我有一些输入,我需要转换成正确的中文字符,但我想我停留在最后的数字到字符串的转换。我已使用e6b9af与文本湯 MWE 下面是我为说明这个问题而做的一个小例子。输入是“%e6%b9%af”(从其他地方的URL获取) #包括 #包括 std::字符串尝试(std::字符串路径) { std::size\u ti=path.find(“%”); while(i!=std::string::npos) { std::string sub=path.substr(i,9); 子项擦除(i+6,1); s

我有一些输入,我需要转换成正确的中文字符,但我想我停留在最后的数字到字符串的转换。我已使用
e6b9af
与文本

MWE 下面是我为说明这个问题而做的一个小例子。输入是
“%e6%b9%af”
(从其他地方的URL获取)

#包括
#包括
std::字符串尝试(std::字符串路径)
{
std::size\u ti=path.find(“%”);
while(i!=std::string::npos)
{
std::string sub=path.substr(i,9);
子项擦除(i+6,1);
sub.erase(i+3,1);
第(i,1)款;
std::size_t s=std::stoul(sub,nullptr,16);
替换(i,9,std::to_字符串);
i=路径。查找(“%”);
}
返回路径;
}
int main()
{
std::string input=“%E6%B9%AF”;
标准::字符串目标=”湯";
//将输入转化为目标
输入=尝试(输入);

std::cout基于您的建议,并将示例从更改为。这就是我想到的

#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;
}
#包括
#包括
#包括
标准::字符串解码\u url(常量标准::字符串和路径)
{
std::stringstream解码;
对于(std::size_t i=0;i解码字节
E6 B9 AF
是您在此处发布的字符的UTF-8编码。更正确的实现方法是先撤消URL编码,然后根据需要进行UTF-8解码。如果您只是想将其输出到需要UTF-8的处理器,则只需进行URL解码。至于最后一个问题,请参阅您使用
进行解码_string
将数字转换为以10为基数的字符串表示形式。实际上,您需要的是将该数字转换为单个字符。由于您已将其转换为2位十六进制值,因此它保证在正确的范围内,因此只需将其转换为
char
并将其粘贴到字符串中即可。@Botje感谢您的建议好的读物是:)
#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;
}