文字列「12233456」がある場合
「\x12\ x23 \ x34 \ x56」に変更する最も簡単な方法は何ですか?
string s = "12 23 34 45";
stringstream str(s), out;
int val;
while(str >> val)
out << "\\x" << val << " "; // note: this puts an extra space at the very end also
// you could hack that away if you want
// here's your new string
string modified = out.str();
あなたの質問はあいまいです、それはあなたが実際に何を望んでいるかによって異なります:
結果を char s[] = { 0x12, 0x34, 0x56, 0x78, '\0'}: と同じにしたい場合は、次のようにします。
std::string s;
int val;
std::stringstream ss("12 34 56 78");
while(ss >> std::hex >> val) {
s += static_cast<char>(val);
}
この後、これでテストできます:
for(int i = 0; i < s.length(); ++i) {
printf("%02x\n", s[i] & 0xff);
}
印刷されます:
12
34
56
78
それ以外の場合、文字列を文字通り "\x12 \x23 \x34 \x56" にしたい場合は、Jesse Beder が提案したことを実行できます。
あなたはそのようにこれを行うことができます:
foreach( character in source string)
{
if
character is ' ', write ' \x' to destination string
else
write character to destination string.
}
std :: stringを使用することをお勧めしますが、これは、最初に文字列をチェックして空白の数を数え、次にその数x3になる新しい宛先文字列を作成することで簡単に実行できます。