tags:

views:

78

answers:

1

Given an input like

a { b c d { e f } g }

I want to parse it one token at at time (letter or brace). When I hit the first closing brace } I need to know how many elements there were since the last opening brace (e and f = 2). And then when I hit the one after that, I need 4 (b,c,d,g).

Grabbing the tokens 1 by 1 is easy, but... I don't know how to count them. I was thinking about Stack<int> but I can't modify the top element to increment it?

+8  A: 

Rather than trying to modify the top element, why not keep that one just in an int variable.

  • When you see an opening brace, push your "count so far" onto the stack, and set the count to 0.
  • When you see a letter, increment your "count so far"
  • When you see a closing brace, do whatever you need to with the count, and pop the stack to get the new "count so far" value

EDIT: If you wanted to keep all the state in the stack itself, you can always think of the top element as a variable, which is changed by performing pop-increment-push. At that point, the operations are:

  • Opening brace: push 0
  • Letter: pop-increment-push
  • CLosing brace: pop, use value however you want to before it vanishes forever

This is likely to be very slightly less efficient, but I think it's actually more elegant.

Jon Skeet
Ah!! Of course. Clever! Thanks Mr. Skeet!
Mark
I was thinking up a solution using a recursive method that would work it's way inward, but I think this is a better solution since it's simpler, and the readability should be better.
Øyvind Bråthen
I started on the pop-increment-push solution just before you posted this answer, but I actually found it to be less elegant. Turns out it's nice to be able to use the top count without having to peek :)
Mark