Strtok and replace substring in C ++

If I have the string "12 23 34 56"

What's the easiest way to change it to "\ x12 \ x23 \ x34 \ x56"?

+1


source to share


3 answers


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 your new string
string modified = out.str();

      



+2


source


In doubt, it depends on what you really want:

if you want the result to be the same: char s [] = {0x12, 0x34, 0x56, 0x78, '\ 0'}: then you can do this:

std::string s;
int val;
std::stringstream ss("12 34 56 78");
while(ss >> std::hex >> val) {
   s += static_cast<char>(val);
}

      

after that you can check it like this:



for(int i = 0; i < s.length(); ++i) {
    printf("%02x\n", s[i] & 0xff);
}

      

which will print:

12
34
56
78

      

otherwise, if you wanted your string to literally be "\ x12 \ x23 \ x34 \ x56", you could do what Jesse Beder suggested.

+2


source


You can do it like this:

foreach( character in source string)
{
  if 
    character is ' ', write ' \x' to destination string
  else 
    write character to destination string.
}

      

I suggest using std :: string, but it can be done easily by first checking the string to count the number of spaces and then creating a new destination string as number x3.

0


source







All Articles