简体   繁体   English

在C#中解析字符串中的多个双精度数

[英]Parse multiple doubles from string in C#

I have a string that contains a known number of double values. 我有一个包含已知数量的double值的字符串。 What's the cleanest way (via C#) to parse the string and plug the results into matching scalar variables. 解析字符串并将结果插入匹配的标量变量的最简洁方法(通过C#)是什么? Basically, I want to do the equivalent of this sscanf statement, but in C#: 基本上,我想做相当于这个sscanf语句,但在C#中:

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

... assuming that " textBuff " might contain the following: ...假设“ textBuff ”可能包含以下内容:

"-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. 谢谢你的任何指示。

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]);

You can use String.Split(' ', StringSplitOptions.RemoveEmptyEntries) to split it into "single values". 您可以使用String.Split('',StringSplitOptions.RemoveEmptyEntries)将其拆分为“单个值”。 Then it's a straight Double.Parse (or TryParse) 然后它是一个直的Double.Parse(或TryParse)

foreach( Match m in Regex.Matches(inputString, @"[-+]?\d+(?:\.\d+)?") )
    DoSomething(m.Value);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM