如果我有一个字符串“12 23 34 56”
将其更改为“\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。