Jump to content
Xtreme .Net Talk

sscanf - is there a .net equivilent? (or a good way to parse strings?)


Recommended Posts

Posted

Hi,

 

I've been looking through the docs, but i havn't been able to find anything which can do what the C function sscanf() does.

(please dont confuse with scanf(), which is a fileio function. sscanf is a string parsing function)

 

Does anyone know if there is a class that can take a format, a string and some objects, and put the values it finds (according to the format) in the string, in the objects? (exactly what sscanf does)

 

Thanks.

  • *Experts*
Posted

String.Format will do the trick. It uses named parameters, such as {0}, {1}, etc. Check the help, but here's a sample:

 

Debug.WriteLine(String.Format("Hello {0}. You are {1} years old", "Dan", 31));

 

-Nerseus

"I want to stand as close to the edge as I can without going over. Out on the edge you see all the kinds of things you can't see from the center." - Kurt Vonnegut
  • *Experts*
Posted

Ah, I didn't read it close enough. You were right the first time, regular expressions with the Matches collection. :)

 

-ner

"I want to stand as close to the edge as I can without going over. Out on the edge you see all the kinds of things you can't see from the center." - Kurt Vonnegut
Posted

ok... are there .net regular expressions to match the value types?

(to provide the functionality to match sscanf :P)

 

so, for example, if i had a string which was made up of, say; a string, an int32, a single, another int32, and a double

(eg "hello 45626 0.63735 463573 1654.2563656464"), would i be able to match it with something like "%s %i %f %i %d" ?

 

(cause when i looked in the docs, i couldnt find a page that listed regular expressions which allowed for the use of value types, i could only find string pattern matching stuff)

 

Thanks.

  • *Experts*
Posted

If indeed every piece of info is separated by a space, there's you regular expression match. As divil said, it won't do type conversions automatically but if you know the type in C/C++ (%f %s, etc.) then you can call the appropriate Convert.Toxxx function or whatever you like (Int32.Parse(), etc.). Regular expressions can match in other ways than just spaces, of course - I'd take a look at the help file on them for some basic info to get started.

 

-Nerseus

"I want to stand as close to the edge as I can without going over. Out on the edge you see all the kinds of things you can't see from the center." - Kurt Vonnegut

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...