Simulating sscanf parsing in C#

R

Ray Mitchell

Hello,

With the C# Format method I can create strings from both literal text and
values of ints, floats, doubles, and the like. Being new to C#, I assume
there is also a way to control field widths, base, precision, etc. in
Format. What I need is a similar function to parse a string and extract
various fields. In C, using sscanf, it is trivial using the various
conversion specifications. I've done it in C# by writing my own
character-oriented state machines and I assume regex could also be used, but
is there something simpler, like a Format counterpart?

Thanks,
Ray Mitchell
 
C

Chris Taylor

Hi,

Unfortunately there is not C# function similar to sscanf. You would have to
either parse the input yourself, you could use regex, and split functions to
help with the parsing. Alternatively you might be able to use P/Invoke, but
I believe you will have to resort to the undocumented __arglist for this. Of
course, someone might have done all this already so there might be library
you could use.

Hope this helps

Chris Taylor
 
A

AlexS

Take a look at various Parse methods, like int.Parse, Boolean.Parse,
Byte.Parse etc.

HTH
Alex
 
R

Ray Mitchell

Thanks! Yes, the Parse methods almost do it. However, in sscanf there is a
way to find out how many characters have been inspected when the parse is
complete so another parse can be started from that point. Is there a way to
determine this using the C# parses?
 
A

AlexS

I don't think so.

However, if you really need to split string into substrings using variety of
formats - I would strongly suggest to use Regex. It's not that complex once
you know how to specify regular expression.

Would be interesting to see example of format, which is easily parsed by
sscanf and not by Regex.

HTH
Alex
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top