从解析字符串在C#中的多个双打 [英] Parse multiple doubles from string in C#

查看:101
本文介绍了从解析字符串在C#中的多个双打的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含已知数量的双值的字符串。什么是最干净的方式(通过C#)来解析字符串和结果插入到匹配的标量变量。基本上,我想做的这个相当于的sscanf 语句,但在C#中:

 的sscanf(textBuff,%LG%LG%LG%LG%LG%LG,&安培; X,&安培; Y,放大器; Z,和功放I,功放;Ĵ,&安培; K); 



...假设 textBuff 可能包含以下内容:

 
-1.123 4.234 34.12 126.4 99 22

...这的每一个值之间的空格字符数可能会发生变化的指针。



感谢。


解决方案

 字符串textBuff =-1.123 4.234 34.12 126.4 99 22; 

双击[]结果= textBuff
.Split(新的char [] {''},StringSplitOptions.RemoveEmptyEntries)
。选择(S = GT; double.Parse(S ))
.ToArray();

双X =导致[0];
// ...
双K =导致[5];

 字符串textBuff =-1.123 4.234 34.12 126.4 99 22; 

的String []结果= textBuff
.Split(新的char [] {''},StringSplitOptions.RemoveEmptyEntries);

双X = double.Parse(结果[0]);
// ...
双K = double.Parse(结果[5]);


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.

解决方案

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

这篇关于从解析字符串在C#中的多个双打的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆