I want to get a string contained within a string where every time I see (xxx)
I will get only xxx.
I am trying to do it in a recursive manner with a function int find(char* str) for example.
The function will return 1 if there are no '(' or ')' left (all removed), and 0 otherwise.
the string can remain as is, just need to check the stated conditions.
OK input: (xxx)(zzz(yyy)zzz)
BAD input: xx(x(zzz)(y
How can this be done in C?
A simple stack is a good way to solve this. Every time you see a ‘(‘ push onto the stack. Every time you see a ‘)’ pop off the stack. If you ever try to pop off an empty stack or have things left on the stack when you are done, then the input was bad.
Edit: you could also do the same thing with a counter. Increment and decrement respectively. If the counter ever goes negative, return false. Otherwise, when you are done return true if you are at 0, or false otherwise. So the counter just represents the size of the ‘stack’.