std::string substr method problems

2019-07-24 04:34发布

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?

2条回答
闹够了就滚
2楼-- · 2019-07-24 04:51

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.

查看更多
霸刀☆藐视天下
3楼-- · 2019-07-24 04:51

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);
}
查看更多
登录 后发表回答