tags:

views:

85

answers:

2

I have a string in the following format: "R: 625.5m E:-32768m"

What's the most efficient way to pull out the 625.5?

+1  A: 

sscanf is a good candiate to parse simple strings with fixed format.

Eiko
OP searching most efficient way
Svisstack
@Svisstack: see the comments. He wants "quick and dirty", not "three milliseconds faster than `sscanf`". `sscanf` *is* the correct answer.
Randolpho
Hmm... getting downvoted today without any reason?! sscanf isn't awfully inefficient, and efficiency comes in a lot of flavors - development time is often as important as runtime consideration.
Eiko
@Svisstack: but hasn't said whether he cares more about run-time efficiency or programmer efficiency, nor whether he needs the result as a string or a number, nor how much the string may vary, whether he's okay with modifying the original string, etc. Without knowing all of that, `sscanf` is about as good a choice as any and better than most (certainly much more reasonable than anything that involves modifying the input).
Jerry Coffin
`*scanf` have enough surprises hidden in their definition that they should, IMO, never be used.
Zack
+1  A: 

Your best bet is to use sscanf to read formatted information from the string.

sscanf(mystr, "R: %f", &myFloat);
Randolpho
And - just like with regular expressions - now you have two problems.
Zack
@Zack: parsing was already the problem. Regular expressions are the problem on top of that parsing problem.
Randolpho
What I meant was, `*scanf` are *also* a problem on top of the original parsing problem. See my responses to other answers.
Zack
Works perfectly. Thanks guys. 1. Trim off the R: 2. Trim off an arbitrary amount of whitespace. 3. Use sscanf
FoppyOmega
@Zack: Assuming i18n isn't an issue (although it's a valid edge case), sscanf isn't nearly as bad as you're making it out to be.
Randolpho
i18n always ends up being an issue eventually, in my experience.
Zack
@Zack: true enough.
Randolpho