我正在与测量仪器通信,它以单个字符串返回数据。输出如下:
string result = "-3.546714E-10A,+0.000000E+00,+5.120000E+02\n";
所以我有兴趣在这个字符串中得到的是第一部分和第二部分。第一部分是 Current in Ampere,第二部分是 TimeStamp(测量时间)。
我正在尝试这段代码,但它不起作用:
temp = result.Split(',');
tipair = new Results.TIPair();
tipair.Current = float.Parse(temp[0]);
tipair.Time = float.Parse(temp[1]);
理想情况下,我希望电流为 -3.546714E-10
,时间为 0
(时间可以是任何正数)。
更新:我试着像下面那样做,但我得到了非常糟糕的数字(比他们应该的大得多!)
temp = result.Split(',');
tipair = new Results.TIPair();
tipair.Current = float.Parse(temp[0].Substring(0, temp[0].Length - 1));
tipair.Time = float.Parse(temp[1]);
最佳答案
您可以使用 Double.Parse() 解析电流有效 Number Styles :
string result = "-3.546714E-10A,+0.000000E+00,+5.120000E+02\n";
var parts = result.Split(',');
double current = double.Parse(parts[0].Remove(parts[0].Length - 1),
NumberStyles.AllowExponent | NumberStyles.Number);
double time = double.Parse(parts[1],
NumberStyles.AllowExponent | NumberStyles.Number);
MSDN,NumberStyles Enumeration :
AllowExponent Indicates that the numeric string can be in exponential notation. The AllowExponent flag allows the parsed string to contain an exponent that begins with the "E" or "e" character and that is followed by an optional positive or negative sign and an integer. In other words, it successfully parses strings in the form nnnExx, nnnE+xx, and nnnE-xx. It does not allow a decimal separator or sign in the significand or mantissa; to allow these elements in the string to be parsed, use the AllowDecimalPoint and AllowLeadingSign flags, or use a composite style that includes these individual flags.
关于c# - 将一个复杂的字符串分成 3 部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7927031/