string substr方法问题
std::string substr method problems
你好,我正在写这个方法。我想让它从一个给定的缓冲区中提取一部分在一个给定的位置。我有一个像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 + 1
和b_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);
}
相关文章:
- 最小硬币更换问题(自上而下方法)
- 使用同一类中的方法重新分配字段时出现问题
- 我想直接在结构中插入,但没有一种方法可以正确避免填充问题
- Protobuf中重复字段的问题.使用重复字段进行序列化/反序列化的更好方法是什么?
- 此动态编程问题的自上而下方法
- 此解决方案中生成更改的方法数量(自上而下)有什么问题?
- 使用模板方法为标头提供空 cpp 时出现问题
- 这种针对 N Queen 问题的回溯方法不正确吗?
- C++ push() 和 pop() 方法使用指针的动态 LinkedList 的问题
- CreateFileA方法出现问题
- 必须使用尾随返回类型的示例,因为无法用旧方法解决问题
- 双重检查创建单例问题的方法
- C++ 指针问题 - 通过方法更新指针
- C++隐式/显式模板方法专用化问题
- 迭代快速排序方法的分区算法问题
- 单独的类声明和方法定义文件问题
- 我通过迭代加法将二进制数转换为十进制并检查单个字符(请参阅代码)的方法有什么问题?
- 如何通过动态规划方法解决这个问题?
- C++ 03 类模板 这是转换构造函数还是转换运算符?以及如何声明解决此问题的方法
- 一个c++语法问题:方法的类