# Parsing a string

This topic is 4653 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I am trying to figure out the best way to parse a string that I use to roll dice in a RPG. Anyone who plays will know what I am talking about. ie. d4, 2d8, 4d6+6 and 2(d20+2)+6. Any suggestions would be helpful. Thanks. theTroll

##### Share on other sites
What language are you planning on using? The method in C++ is quite different from say... perl.

##### Share on other sites
It will be in C#, but you could reply in c++ or VB if you wanted to.

Thanks..
theTroll

##### Share on other sites
strtok

Though that's only simple and easy for the first couple of cases. For the last case, you might gain some ease-of-use from Boost.Tokenizer

##### Share on other sites
You haven't mentioned what programming language you want to use. I recently did something similar in Prolog which was loads of fun.

Anyway, the basics are the following:
• You need to define the basic terms of which your string is comprised. Judging by the content, these will either be a die string or a number.

• Afterwards, implement a recursive method which will build a binary tree out of your string. The tree's nodes will be composite terms, which are defined as any valid expression built from basic terms. The tree's leaves must be basic terms.

• Each parent node will define an operation on his children. In this case, either addition or multiplication

• Evaluation of the expression in the root will involve traversing the tree

EDIT: The above just might be overkill.

##### Share on other sites
The die and the multiplier are pretty easy. The biggest problem I am having is figuring out the parenthesis, a single parenthesis is pretty easy but once I get into multiples then it starts getting complicated.

theTroll

##### Share on other sites
I would build a tree out of it.

Ex: 2(d20+2)+6

       ADD      /  \    MULT   6   /  \   2   ADD      / \     d20  2

Then build the result from the bottom up.

##### Share on other sites
Regular expressions and compiler theory. There's plenty of tools that generate those for you. Lex/Yacc, Bison, and I simply forgot the other alternatives right now.

My personal tool of choice is Lex/Yacc combo, since I never had problems finding it's port to any language/platform I used.

In addition, I prefer to let them generate the optimal syntax/parse tree, then I hand-code the state machine for minimum clutter. A typical state machine for parsing this will be under 100 lines of code.

And since you mentioned C#, look at this: http://fisheye1.cenqua.com/viewrep/~raw,r=1.4/d20sharp/d20Sharp/Dice.cs

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 15
• 14
• 46
• 22
• 27
• ### Forum Statistics

• Total Topics
634048
• Total Posts
3015237
×