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();
}
curItem 变量包含如下值:检测到的云:距海岸 0.9174312 公里。
我只想从值中获取 0.9174312 并将其设置在变量 xCoord 中。 问题是它现在进行解析的方式出现错误:
输入的字符串格式不正确
我猜索引不应该为零。如何只从字符串中获取 float ?
现在这个字符串格式每次都是一样的:
第一部分: 检测到的云:第二部分:0.9174312 和最后一部分:距海岸公里数。
但也许将来我会更改字符串格式,因此我需要在任何地方将 float 放在字符串的中间或开头以仅获取 float 。
最佳答案
考虑使用正则表达式。
var match = Regex.Match(val, @"([-+]?[0-9]*\.?[0-9]+)");
if (match.Success)
xCoord = Convert.ToSingle(match.Groups[1].Value);
关于c# - 如何只解析字符串中的 float ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25841586/