C++ 在两个迭代器之间获取`std::string`的子字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10004395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:30:04  来源:igfitidea点击:

Getting a substring of a `std::string` between two iterators

c++stringparsing

提问by ely

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:

我有一个程序,它希望将一些选项作为输入,以指定形式 (p1, p2, p3, ... ) 中的概率。所以命令行用法实际上是:

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

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.

我想在 C++ 中解析这样的列表,我目前正在尝试使用 std::string 类型的迭代器和 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(", "));

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

注意上面的<what to put here?>部分。由于我需要忽略开头和结尾的括号,我想做类似的事情

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

but it doesn't look like substrworks 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 substrto call

我的一个想法是进行迭代器算术,如果允许的话,并用于substr调用

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.

但我不确定这是否被允许,或者这是否是一种合理的方式。如果这不是一种有效的方法,那么什么是更好的方法?...提前谢谢了。

回答by Pubby

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

std::string的构造函数应该提供您需要的功能。

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