简体   繁体   中英

Parse a string with key-value pairs where there is no char between key and value c#

I am trying to parse through a file line by line, each time setting variables equal to a value from the line.

Example lines would be:

G1 Z0.500 F7800.000
G1 X-0.336 Y13.564 F7800.000
G1 X3.205 Y13.493 E3.63071 F1800.000

I would have variables like:

double x;
double y;
double z;

Say I parse the first line, my output should be:

x = 100000;
y = 100000;
z = 0.5;

If I parsed the second line, my output should be:

x = -0.336;
y = 13.564;
z = 100000;

The third line is just another line that could come up, but all are fairly similar. If the key doesn't appear in the string, the values are set to 100,000.

I attempted to use code like this:

char[] delimiters = { 'X', 'Y', 'Z'};
string[] words = line.Split(delimiters);

but that returned for the first line:

z = 0.500 F7800.000

What would be the best way to go about parsing each line for these key value pairs?

This should get you started...

        using (StreamReader sr = new StreamReader("data.txt"))
        {
            while (!sr.EndOfStream)
            {
                string line = sr.ReadLine();
                if (line != null)
                {
                    string[] items = line.Split(' ');
                    decimal? x, y, z = null;
                    for (int i = 1; i < items.Length; i++)
                    {
                        if (items[i].ToLower().StartsWith("x"))
                        {
                            x = decimal.Parse(items[i].Substring(1));
                            Console.WriteLine($"x = {x}");
                        }
                        else if (items[i].ToLower().StartsWith("y"))
                        {
                            y = decimal.Parse(items[i].Substring(1));
                            Console.WriteLine($"y = {y}");
                        }
                        else if (items[i].ToLower().StartsWith("z"))
                        {
                            z = decimal.Parse(str);
                            Console.WriteLine($"y = {z}");
                        }
                        else
                        {
                            continue;
                        }
                    }
                }
            }
        }

One thing you could do is create a simple class that represents the data you care about, which appear to be X , Y , and Z . Then you can create a static method that knows how to create an instance of the class from a string.

For example:

public class XYZData
{
    public double X { get; set; }
    public double Y { get; set; }
    public double Z { get; set; }

    public static XYZData Parse(string input)
    {
        var xyzData = new XYZData { X = 100000, Y = 100000, Z = 100000 };

        if (string.IsNullOrWhiteSpace(input)) return xyzData;

        var parts = input.Split();

        foreach (var part in parts)
        {
            double result;

            if (part.Length < 2 || 
                !double.TryParse(part.Substring(1), out result)) 
            {
                continue;
            }

            if (part.StartsWith("X", StringComparison.OrdinalIgnoreCase))
            {
                xyzData.X = result;
                continue;
            }
            if (part.StartsWith("Y", StringComparison.OrdinalIgnoreCase))
            {
                xyzData.Y = result;
                continue;
            }
            if (part.StartsWith("Z", StringComparison.OrdinalIgnoreCase))
            {
                xyzData.Z = result;
                continue;
            }
        }

        return xyzData;
    }
}

Then you can populate a list of these things when reading your file:

var filePath = @"f:\public\temp\temp.txt";

var data = new List<XYZData>();

foreach (var fileLine in File.ReadLines(filePath))
{
    data.Add(XYZData.Parse(fileLine));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM