开发者

How to parse a text file?

开发者 https://www.devze.com 2022-12-17 12:46 出处:网络
Basically I need someone to help m开发者_如何转开发e or show me the code that will allow me to read a name and a price from a file i have called c1.txt.

Basically I need someone to help m开发者_如何转开发e or show me the code that will allow me to read a name and a price from a file i have called c1.txt.

This is what i already have.

    TextReader c1 = new StreamReader("c1.txt");
        if (cse == "c1")
        {
            string compc1;
            compc1 = c1.ReadLine();
            Console.WriteLine(compc1);
            Console.WriteLine();
            compcase = compc1;
            compcasecost = 89.99;
        }

also how to select a line to read from a text document would be great.


You haven't told us the format of the text file. I am going to assume the following:

Milk|2.69
Eggs|1.79
Yogurt|2.99
Soy milk|3.79

You also didn't specify the output. I am going to assume the following:

Name = Milk, Price = 2.69
Name = Eggs, Price = 1.79
Name = Yogurt, Price = 2.99
Name = Soy milk, Price = 3.79

Then the following will read such a file and produce the desired output.

using(TextReader tr = new StreamReader("c1.txt")) {
    string line;
    while((line = tr.ReadLine()) != null) {
        string[] fields = line.Split('|');
        string name = fields[0];
        decimal price = Decimal.Parse(fields[1]);
        Console.WriteLine(
            String.Format("Name = {0}, Price = {1}", name, price)
        );
    }
}

If your separator is different then you need to change the parameter '|' to the method String.Split (invoked on the instance of String named line as line.Split('|')).

If your format needs to be different then you need to play with the line

String.Format("Name = {0}, Price = {1}", name, price)

Let me know if you have any questions.


You can also try using a parsing helper class as a starting point, such as the one described at http://www.blackbeltcoder.com/Articles/strings/a-text-parsing-helper-class.


    static void ReadText()
    {
        //open the file, read it, put each line into an array of strings
        //and then close the file
        string[] text = File.ReadAllLines("c1.txt");

        //use StringBuilder instead of string to optimize performance
        StringBuilder name = null;
        StringBuilder price = null;
        foreach (string line in text)
        {
            //get the name of the product (the string before the separator "," )
            name = new StringBuilder((line.Split(','))[0]);
            //get the Price (the string after the separator "," )
            price = new StringBuilder((line.Split(','))[1]);

            //finally format and display the result in the Console
            Console.WriteLine("Name = {0}, Price = {1}", name, price);
        }

It gives the same results as @Jason's method, but I think this is an optimized version.

0

精彩评论

暂无评论...
验证码 换一张
取 消