Saturday, February 19, 2011

strtok and replace a substring in C++

If I have a string "12 23 34 56"

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

From stackoverflow
  • 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();
    
    Evan Teran : it avoid the extra space, just prepend a "\x" before you start and change the line in the while to be: out << " \x" << val;
    Evan Teran : though from his comments, it looks like he wants a string with chars 0x12, 0x34, 0x56, 0x78 not a string containing "\x12 \x34 \x56 \x78".
    Martin York : You mean "\\x"
    Jesse Beder : Whoops, I just noticed that; thanks for the edit, Evan.
  • You can do this like so:

    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 this can be done easily by first checking the string to count how many whitespaces and then create your new destination string to be that number x3.

  • You question is ambiguous, it depends on what you actually want:

    if you want the result be the same as: char s[] = { 0x12, 0x34, 0x56, 0x78, '\0'}: then you could 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 this, you can test it with 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 want your string to literally be "\x12 \x23 \x34 \x56" then you could do what Jesse Beder suggested.

0 comments:

Post a Comment