3

I have a string that contains a known number of double values. What's the cleanest way (via C#) to parse the string and plug the results into matching scalar variables. Basically, I want to do the equivalent of this sscanf statement, but in C#:

sscanf( textBuff, "%lg %lg %lg %lg %lg %lg", &X, &Y, &Z, &I, &J, &K );

... assuming that "textBuff" might contain the following:

"-1.123    4.234  34.12  126.4  99      22"

... and that the number of space characters between each value might vary.

Thanks for any pointers.

dtb
  • 213,145
  • 36
  • 401
  • 431
Jeff Godfrey
  • 718
  • 8
  • 18

3 Answers3

18
string textBuff = "-1.123    4.234  34.12  126.4  99      22";

double[] result = textBuff
    .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
    .Select(s => double.Parse(s))
    .ToArray();

double x = result[0];
//    ...
double k = result[5];

or

string textBuff = "-1.123    4.234  34.12  126.4  99      22";

string[] result = textBuff
    .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

double x = double.Parse(result[0]);
//    ...
double k = double.Parse(result[5]);
dtb
  • 213,145
  • 36
  • 401
  • 431
  • 2
    Think you need a lambda for that select. Select(x => double.Parse(x)) should work. – Ty. Sep 10 '09 at 16:18
  • 1
    @Ty - the code shown will work. The lamba is exchangeable for the method group itself. – Drew Noakes Sep 10 '09 at 16:20
  • 1
    @Drew: Ty is right. "The type arguments for method ...Select... cannot be inferred from the usage. Try specifying the type arguments explicitly." I've fixed that. – dtb Sep 10 '09 at 16:22
  • The first option really cut a lot out of my own code just now. Thanks dtb. And Ty is absolutely correct. – Kawa Sep 10 '09 at 16:26
4

You can use String.Split(' ', StringSplitOptions.RemoveEmptyEntries) to split it into "single values". Then it's a straight Double.Parse (or TryParse)

Hans Kesting
  • 38,117
  • 9
  • 79
  • 111
0
foreach( Match m in Regex.Matches(inputString, @"[-+]?\d+(?:\.\d+)?") )
    DoSomething(m.Value);
csharptest.net
  • 62,602
  • 11
  • 71
  • 89
  • 3
    The answer to the question is moved to DoSomething(), and it won't accept 1E6 etc. – H H Sep 10 '09 at 16:23