Pass a string Recursively without Recreation

后端 未结 2 1952
抹茶落季
抹茶落季 2020-12-07 06:01

I answered a question here: https://stackoverflow.com/a/28862668/2642059 Where I needed to use recurrence to step through a string. I wanted to use a cons

2条回答
  •  情书的邮戳
    2020-12-07 06:42

    string_view from the library fundamentals TS might be one idea, support is available in GCC.

    The interface is virtually identical to string

    #include 
    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.

提交回复
热议问题