An alternative approach is to iterate over each charactor; when you see a ( push it on the stack array (and change some "state" variable, maybe a "depth count" which is also the size of the stack); then when you see a ), pop the top of the stack (will be a (). Based on the depth of the nesting (or size of the stack) you can do all sorts of things with the intervening characters you see.