Find String Inside Outermost Parenthesis

旧时模样 提交于 2019-11-28 14:36:00

Pseudo code:

 iterate over chars
 if char is (
   increment counter
   store position of first ( only
 if char is )
   decrement counter
   if counter == 0
      use index of current char and position of first ( to get substring

Lest pseudo code be the only answer I've taken it upon myself to answer this using standard algorithms. Given const string foo{ "this (is(maybe)) a test (and maybe not)" } can be used to solve like this:

const auto start = find(cbegin(foo), cend(foo), '(');
const auto finish = find_if(start, cend(foo), [count = 0](const char i) mutable {
    if (i == '('){
        count++;
    }
    else if (i == ')'){
        count--;
    }
    return count <= 0; });

From here, if both start and finish are not cend(foo) the string is valid and can be obtained from string(next(start), finish) (Live Example).

It's possible that this is as good a solution as there is in C++. I guess it is just wishful thinking that there's something out there to match parentheses and find the value.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!