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

matt
  • 4,042
  • 5
  • 32
  • 50

3 Answers3

5

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
  • 733,204
  • 149
  • 1,241
  • 1,454
  • I assume that StringSplitOptions.RemoveEmptyEntries option would effectively allow any number of spaces to separate the entries? – matt Aug 05 '10 at 04:44
  • 1
    Now if only we could do `a, b, c = astring.Split(' ', ...).Select(Int32.Parse);` – Gabe Aug 05 '10 at 04:44
0

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
  • 5,237
  • 3
  • 23
  • 26
0

Alternatively, it's fairly straight forward to write your own version of sscanf() in C#. The syntax makes it reasonably easy to implement.

I implemented my own version and posted on the web. You can view it here.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466