如何将 3 个浮点数从字符串获取到结构的新实例

本文关键字:新实例 结构 实例 获取 浮点数 字符串 | 更新日期: 2023-09-27 18:36:23

我有.txt格式的文件,坐标如下:

Ver(0.6039f, 0.8431f, 0.8980f)

我需要最好的方法来从这个Ver(0.6039f, 0.8431f, 0.8980f)一个新的Point3D();

public struct Point3D
{
    float x,
          y,
          z;
    public Point3D(float x, float y, float z)
    {
        this.x = x;
        this.y = y;
        this.z = z;
    }
}

如何将 3 个浮点数从字符串获取到结构的新实例

也许你可以这样做:

// read the file into an array of strings - consider File.ReadAllLines() - perhaps name the array it produces "fileLines"
// iterate over the fileLines array processing one array element at a time - a good method would be to use a foreach loop
foreach(string fileLine in fileLines)
{
    // TODO: isolate the part of the string between the parenthesis
    // split the string on commas to create a string array
    var coordinates = fileLine.Split(new char[',']);
    // if there the number of string array elements is correct, allocate a Point3D element
    if (coordinates.length != 3)
    {
        throw new ApplicationException(string.Format("Invalid number of coordinates. Expected 3, got {0}.", coordinates.Length));
    }
    // use float.TryParse() to load each element of the string array into the proper member of its struct or class
    float xCoordinate;
    float yCoordinate;
    float zCoordinate;
    if (! float.TryParse(coordinates[0], out xCoordinate)
    {
        throw new ApplicationException(string.Format("Unable to parse X-coordinate {0}.", coordinates[0]));
    }
    if (! float.TryParse(coordinates[1], out yCoordinate)
    {
        throw new ApplicationException(string.Format("Unable to parse Y-coordinate {0}.", coordinates[1]));
    }
    if (! float.TryParse(coordinates[2], out zCoordinate)
    {
        throw new ApplicationException(string.Format("Unable to parse Z-coordinate {0}.", coordinates[2]));
    }
    Point3D point3D = new Point3D(xCoordinate, yCoordinate, zCoordinate);
    // TODO: stuff this point3D into an array or collection to save it
    // process the next line of the file...
}

我将把它留给读者一个练习,以填写注释之间的一些代码。

编辑:我已经回去填写了一些细节。 请注意,此代码的结构和编写方式尽可能紧凑,以免混淆读者。