std::string substr 方法问题 [英] std::string substr method problems

查看:25
本文介绍了std::string substr 方法问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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"

这是我的想法:

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 方法

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?

推荐答案

代码应该看起来像:

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 需要一个起始位置和一个长度.也许是这样的:

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;

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

不过,我不确定 a_pos + 1b_pos + 1 是否正确.确定这就是您想要的.

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

这篇关于std::string substr 方法问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆