c++ - 递归传递字符串而不需要重新创建

标签 c++ string recursion construction char-pointer

我在这里回答了一个问题:https://stackoverflow.com/a/28862668/2642059我需要使用循环遍历 string 的地方。我想在每个函数上使用 const string& 作为我的参数,但除非我想在每次递归时重建字符串,否则我发现我需要传递 startfinish 位置以及 string 本身。所以传递 string 变得毫无意义。

最后,我选择将 startfinish 指针传递给 char[]


举个例子,假设我得到一个包含嵌套括号的字符串(但没有并排的括号插入)。就像这样:

(abc(def(ghi((j)klm)nop)qrs)tuv)wxyz

但不是这样的:

(abc(def)(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));
}

但是,我不高兴为 foo 的每次重复重建一个 string。另一种方法是像链接示例中那样传递 startfinish 指针(或传递 string::const_iterator。)

是否有包装器或其他东西可以让我使用 string 功能,但不能重建 string

最佳答案

string_view来自库基础的 TS 可能是一个想法,GCC 提供支持。

接口(interface)实际上与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;

尽管它们都非常神秘。

关于c++ - 递归传递字符串而不需要重新创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29007753/

相关文章:

c++ - 我无法让 Netbeans C++ 工作,我做错了什么?

Javascript 替换一个字符串

c++ - enable_if + std::less + sizeof... 的组合使 MSVC 失败

c++ - 这个模板代码有什么问题?

c++ - 相等的 C++ STL 容器内容算法

iphone - 字符串匹配 objective-c

java - 在 Java 中连接两个字符串的最快方法是什么?

c++ - 二叉搜索树

c++ - 使用除法技术求数组的最大公约数

c++ - 使用双端队列和递归 C++ 创建所有可能的组合