tags:

views:

94

answers:

4

how do I do this in C#?

int a,b,c;
sscanf(astring,"%d %d %d",&a,&b,&c);

minimal code and dependencies is preferable, is there some built in regex stuff?

I'm using c# 4.0

+2  A: 

If like scannf you are willing to assume that users will give completely correct data then you can do the following.

string astring = ...;
string[] values = astring.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
int a = Int32.Parse(values[0]);
int b = Int32.Parse(values[1]);
int c = Int32.Parse(values[2]);

Regular expressions would work for this scenario but they are a bit overkill. The string can easily be tokenized with the aforementioned Split method.

JaredPar
I assume that StringSplitOptions.RemoveEmptyEntries option would effectively allow any number of spaces to separate the entries?
matt
Now if only we could do `a, b, c = astring.Split(' ', ...).Select(Int32.Parse);`
Gabe
matt: Yes, you are correct.
Gabe
+3  A: 

sscanf Equivalents in C#
http://msdn.microsoft.com/en-us/magazine/cc188759.aspx

Robert Harvey
A: 

The simplest thing I can come up with is this:

var fields = astring.Split(null, StringSplitOptions.RemoveEmptyEntries);
a = int.Parse(fields[0]);
b = int.Parse(fields[1]);
c = int.Parse(fields[2]);
Rafe
A: 

Use Regex.Match(). Better control of field parsing as well and a lot less of the strange behaviors that plague scanf().

siride