如何将带有双反斜杠的字符串转换为单反斜杠

时间:2019-12-18 23:26:34

标签: c++ arrays string byte

如何转换以下字符串:

std::string s = "\\xfc\\xe8\\x82"

等效于char数组:

char s[] = "\xfc\xe8\x82"

1 个答案:

答案 0 :(得分:0)

也许对字符串文字中的转义字符存在普遍的误解。

文字"\\xfc\\xe8\\x82"作为字符串使用“ \”作为转义字符。 “ \”将减少为“ \”。如您所料。因此,如果您打印给定的std::string,则结果将是: \xfc\xe8\x82

因此,您现在要做的是:创建一个包含原始std::string中给出的十六进制值的char数组。

请注意:您的语句char s[] = "\xfc\xe8\x82";将创建一个C样式的char数组,其大小为4,并且包含:

s[0]=fc, s[1]=e8, s[2]=82, s[3]=0

在下面的示例中,我显示了2个转换建议。  1.直接转换  2.使用C ++标准算法

#include <string>
#include <iostream>
#include <iomanip>
#include <regex>
#include <vector>
#include <iterator>
#include <algorithm>


// Hex digit String
std::regex hexValue{R"(\\[xX]([0-9a-fA-F][0-9a-fA-F]))"};


int main ()
{   
    // Source string
    std::string s1 = "\\xfc\\xe8\\x82";
    std::cout << "s 1: " << s1 << "\n";


    // Proposal 1 ------------------------------------------------------

    // Target array
    unsigned char s2[3];

    // Convert bytes from strings
    for (int i=0; i<s1.size()/4; ++i ) {

        // Do conversion. Isolate substring, the convert
        s2[i] = std::strtoul(s1.substr(i*4+2,2).c_str(), nullptr,16);
        // Result is now in s2

        // Output value as tring and decimal value
        std::cout << s1.substr(i*4+2,2) << " -> " << std::hex << static_cast <unsigned short>(s2[i]) 
                  << " -> " << std::dec << static_cast <unsigned short>(s2[i]) << "\n";
    }

    // Proposal 2 ------------------------------------------------------

    // Get the tokens
    std::vector<std::string> vstr(std::sregex_token_iterator(s1.begin(),s1.end(),hexValue, 1), {});

    // Convert to unsigned int
    std::vector<unsigned int> vals{};

    std::transform(vstr.begin(), vstr.end(), std::back_inserter(vals), 
        [](std::string &s){ return static_cast<unsigned>(std::strtoul(s.c_str(), nullptr,16)); } );

    std::copy(vals.begin(), vals.end(), std::ostream_iterator<unsigned>(std::cout,"\n"));

    return 0;
}

第二个解决方案将吃掉字符串中给定数量的十六进制数字