递归地传递一个字符串没有娱乐 [英] Pass a string Recursively without Recreation
问题描述
我在这里回答了一个问题: http://stackoverflow.com/a/28862668/2642059 我需要使用循环来遍历字符串
。我想使用 const string&
作为每个函数的参数,但除非我想重建字符串每个递归,我发现我需要传递一个 start
和 finish
位置以及字符串
本身。因此,根本不通过 string
变得毫无意义。
最后我选择只传递一个 start
和完成
指向 char []
>
例如,假设我得到一个包含嵌套括号的字符串(但没有并排括号插入)。像这样:
(abc(def(ghi((j)klm)nop)qrs)tuv)wxyz
但不是这样:
(abc ghi)(j)(klm)(nop)(qrs)tuv)wxyz
我想编写一个递归程序字符串在最深嵌套的括号中。例如:
string foo(const string& bar){
auto start = bar.find(' )+ 1;
return start == string :: npos + 1?bar:foo(bar.substr(start,bar.find_last_of(')') - start)
}
但是我不高兴重建一个 code>每次重复
foo
。替代方法是传递 start
和完成
指针,如在链接示例中(或传递 string :: const_iterator
s。)
有一个包装器或者什么东西让我使用 string
功能,但不重建
字符串
?
接口实际上与 string
>相同
#include< experimental / string_view>
using std :: experimental :: string_view;
string_view foo(const string_view& bar){
auto start = bar.find('(')+ 1;
return start == string_view npos + 1?bar:foo(bar.substr(start,bar.find_last_of(')') - start));
}
最后一行也可以是
return start? foo(bar.substr(start,bar.find_last_of(')') - start)):bar;
虽然他们都很隐蔽。
I answered a question here: http://stackoverflow.com/a/28862668/2642059 Where I needed to use recurrence to step through a string
. I wanted to use a const string&
as my parameter on each function, but unless I wanted to reconstruct the string each recursion I found that I needed to pass a start
and finish
position as well as the string
itself. So it became pointless to pass the string
at all.
In the end I choose to just pass a start
and finish
pointer to the char[]
.
As an example, say that I'm given a string which contains nested parenthesis (but no side by side parenthetical insertions.) So like this:
(abc(def(ghi((j)klm)nop)qrs)tuv)wxyz
But not like this:
(abc(def)(ghi)(j)(klm)(nop)(qrs)tuv)wxyz
I want to write a recursive program to extract the string in the deepest nested parentheses. Something like:
string foo(const string& bar){
auto start = bar.find('(') + 1;
return start == string::npos + 1 ? bar : foo(bar.substr(start, bar.find_last_of(')') - start));
}
However I'm unhappy reconstructing a string
for each recurrence of foo
. The alternative is to pass start
and finish
pointers as in the linked example (or to pass string::const_iterator
s.)
Is there a wrapper or something which would allow me to use string
functionality, but not reconstruct a string
?
string_view
from the library fundamentals TS might be one idea, support is available in GCC.
The interface is virtually identical to string
#include <experimental/string_view>
using std::experimental::string_view;
string_view foo(const string_view& bar){
auto start = bar.find('(') + 1;
return start == string_view::npos + 1 ? bar : foo(bar.substr(start, bar.find_last_of(')') - start));
}
The last line could also be
return start ? foo(bar.substr(start, bar.find_last_of(')') - start)) : bar;
Although they're both pretty cryptic.
这篇关于递归地传递一个字符串没有娱乐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!