foreach (object item in listBox1.SelectedItems)
{
string curItem = item.ToString();
var parts = curItem.Split("{}XY=, ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
var xCoord = float.Parse(parts[0]);
var yCoord = float.Parse(parts[1]);
var point = new PointF(xCoord, yCoord);
CloudEnteringAlert.pointtocolor.Add(point);
pictureBox1.Invalidate();
}
Run Code Online (Sandbox Code Playgroud)
curItem 变量包含如下值:Cloud detected at: 0.9174312 Kilometers from the coast.
我只想从值中获取0.9174312并将其设置在变量 xCoord 中。问题是它现在进行解析的方式出现错误:
Input string was not in a correct format
我猜索引不应该为零。如何从字符串中只获取浮点数?
现在这个字符串格式每次都是相同的:
第一部分: Cloud detected at: Second part: 0.9174312 and Last part: Kilometers from the coast.
但也许将来我会更改字符串格式,所以我需要在任何地方浮点数将位于字符串的中间最后或开头以仅获取浮点数。
考虑使用正则表达式。
var match = Regex.Match(val, @"([-+]?[0-9]*\.?[0-9]+)");
if (match.Success)
xCoord = Convert.ToSingle(match.Groups[1].Value);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6938 次 |
| 最近记录: |