c# - 将一个复杂的字符串分成 3 部分

标签 c# string split

我正在与测量仪器通信,它以单个字符串返回数据。输出如下:

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/

相关文章:

c# - ApiResource与ApiScope与IdentityResource

java - 每次调用 StringBuffer#toString 和 StrinBuilder#toString 都会返回新实例或字符串池中的实例?

javascript - 如何使用 rand 和 split 函数避免特定的 3 元素组合?

python - 将字符串列表拆分为各自的字符 Python

c# - 使用 C# 查询 SQlite 数据库时出现 ConstraintException

c# - ShellEx : Starting Excel minimized or hidden

c# - 在 .NET 4.6.1 上使用 SignalR Core

Python 不考虑字符串中的字符 "c"

python - 转换日期格式保持其类型python

php - 如何用 php 打破数组中的印地语字符串并计算字符串中有多少字母和元音