在两个迭代器之间获取`std :: string`的子字符串 [英] Getting a substring of a `std::string` between two iterators

查看:453
本文介绍了在两个迭代器之间获取`std :: string`的子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序希望可以输入几个选项​​来指定形式(p1,p2,p3,...)的概率.因此,命令行用法实际上是:

I have a program that's expected to take as input a few options to specify probabilities in the form (p1, p2, p3, ... ). So the command line usage would literally be:

./myprog -dist (0.20, 0.40, 0.40)

我想用C ++解析这样的列表,我目前正在尝试使用std :: string类型的迭代器和Boost提供的split函数进行迭代.

I want to parse lists like this in C++ and I am currently trying to do it with iterators for the std::string type and the split function provided by Boost.

// Assume stuff up here is OK
std::vector<string> dist_strs; // Will hold the stuff that is split by boost.
std::string tmp1(argv[k+1]);   // Assign the parentheses enclosed list into this std::string.

// Do some error checking here to make sure tmp1 is valid.

boost::split(dist_strs,  <what to put here?>   , boost::is_any_of(", "));

<what to put here?>部分上方的注释.由于我需要忽略括号的开始和结尾,因此我想做类似的事情

Note above the <what to put here?> part. Since I need to ignore the beginning and ending parentheses, I want to do something like

tmp1.substr( ++tmp1.begin(), --tmp1.end() )

但它看起来不像substr那样工作,而且我无法在文档中找到可以做到这一点的功能.

but it doesn't look like substr works this way, and I cannot find a function in the documentation that works to do this.

我曾经有一个想法是进行迭代算术(如果允许的话),并使用substr进行调用

One idea I had was to do iterator arithmetic, if this is permitted, and use substr to call

tmp1.substr( ++tmp1.begin(), (--tmp1.end()) - (++tmp1.begin()) )

但是我不确定是否允许这样做,或者这是否是合理的方法.如果这不是有效的方法,那么哪个更好呢? ...非常感谢.

but I wasn't sure if this is allowed, or if it is a reasonable way to do it. If this isn't a valid approach, what is a better one? ...Many thanks in advance.

推荐答案

std::string的构造函数应提供所需的功能.

std::string's constructor should provide the functionality you need.

std::string(tmp1.begin() + 1, tmp1.end() - 1)

这篇关于在两个迭代器之间获取`std :: string`的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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