BMBM
BMBM

Reputation: 16023

Parsing string with C - whats the right tool?

I got a string in this format:

Stuff: </value_1/value_2/value_3>; key="value"

What I need parsed out is value_1, value_2 and value_3 along with the key/value pair. value_3 might or might not be present in the string.

What would one use in C in order to get this done?

I thought about sscanf but the values can be of arbitratry size, so they should be allocated dynamically. strtok would have been my next idea, but that probably needs two separate loops to extract the / separated values and the key/value pair… seems tedious but at least doable.

Anyone with more experience in C has any better idea?

EDIT: regex could be an option, but I would prefer standard string functions if possible at all.

Upvotes: 3

Views: 163

Answers (2)

Clifford
Clifford

Reputation: 93556

If you use "</>; =\"" as the delimiter set, then strtok() will work in a single pass, extracting in turn:

Stuff:
value_1
value_2
value_3
key
value

Not sure what Stuff: is or if it is needed in the extraction, or just an elidation on your part.

Upvotes: 1

Zolomon
Zolomon

Reputation: 9795

You could use regular expressions; see Regular Expressions - The GNU C Library.

If you don't know what regular expressions are; see Regular Expressions.

Here's an online regular expression editor (or this one, if you don't have Flash installed), so you can test your regexp!

Upvotes: 1

Related Questions