2

Hello I'm writing this method. I want it to extract from a given buffer a portion that is in a given place. I have a string like this something=one;something=two and I want to get "one"

This is my idea :

static std::string Utils::getHeader( unsigned char * buffer)
{
    std::string *str = new std::string(buffer);

    std::size_t b_pos = str->find("=");
    std::size_t a_pos = str->find(";");

    return str->substr((a_pos + 1) ,(b_pos + 1));
}

but on eclipse I get this error in reference to the std::string substr method

Invalid arguments ...

Candidates are:
std::basic_string<char,std::char_traits<char>,std::allocator<char>> substr(?, ?)

Can someone explain me why I get this error and how I can fix it?

Erik
  • 2,137
  • 3
  • 25
  • 42
fitzbutz
  • 956
  • 15
  • 33

2 Answers2

1

The code should probably look like:

static std::string Utils::getHeader(unsigned char * buffer, size_t size)
{
    if(!buffer || !size)
        return "";

    const std::string str(reinterpret_cast<char*>(buffer), size);

    std::size_t b_pos = str.find("=");
    if(b_pos == std::string::npos)
        throw ...;

    std::size_t a_pos = str.find(";");
    if(a_pos == std::string::npos)
        throw ...;

    if(b_pos > a_pos)
        throw ...'

    return str.substr((a_pos + 1), (b_pos + 1));
}

substr takes a starting position and a length. Maybe something like:

const size_t start = b_pos + 1;
const size_t length = (a_pos + 1) - (b_pos + 1) + 1;

And then, return str.substr(start, length);.

I'm not certain of the a_pos + 1 and b_pos + 1 is correct, though. Be certain that's what you want.

jww
  • 97,681
  • 90
  • 411
  • 885
  • yes you are right. but i don't want the ";" in the substring.. should it be (a_pos - 1) ? – fitzbutz Jul 13 '14 at 20:15
  • First of all you should swap b_pos and a_pos as you are currently finding "something", not "one". Then the correct length = b_pos - a_pos - 1. Other names for a_pos and b_pos are probably appropriate at this time. – Stian Svedenborg Jul 13 '14 at 20:20
  • @Stian - its not clear to me what Giorgio wants to include and exclude. Giorgio can perform the fine tuning once he gets pointed in the right direction. Perhaps you should simply provide an answer? – jww Jul 13 '14 at 20:31
  • i modified the method with the cast but i still get the same error – fitzbutz Jul 13 '14 at 20:39
  • @GiorgioGambino Have you found an answer? I've got the same issue. – Zaimatsu Aug 11 '15 at 12:15
1

Ok, assuming you know that the input string is formatted as you mentioned you probably want something like this:

static std::string Utils::getHeader(const std::string & params) {
    size_t start = params.find('=') +1;          // Don't include =
    size_t length = params.find(';') - start;    // Already not including ';'
    return str.substr(start, length);
}
Stian Svedenborg
  • 1,797
  • 11
  • 27