Parse multiple doubles from string in C#

2020-03-26 02:07发布

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.

标签: c# text parsing
3条回答
我命由我不由天
2楼-- · 2020-03-26 02:25
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]);
查看更多
祖国的老花朵
3楼-- · 2020-03-26 02:35

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

查看更多
劫难
4楼-- · 2020-03-26 02:38
foreach( Match m in Regex.Matches(inputString, @"[-+]?\d+(?:\.\d+)?") )
    DoSomething(m.Value);
查看更多
登录 后发表回答