string substr方法问题

std::string substr method problems

本文关键字:问题 方法 substr string      更新时间:2023-10-16

你好,我正在写这个方法。我想让它从一个给定的缓冲区中提取一部分在一个给定的位置。我有一个像something=one;something=two这样的字符串我想得到" 1 "

这是我的想法:

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));
}

但是在eclipse上,我在引用std::string substr方法时得到这个错误

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

有人能告诉我为什么我得到这个错误,我怎么能解决它?

代码应该看起来像:

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取起始位置和长度。比如:

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

然后,return str.substr(start, length); .

我不确定a_pos + 1b_pos + 1是正确的,虽然。

好的,假设您知道输入字符串的格式如您所述您可能想要这样:

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);
}