1

基本的に、c1.txt という名前のファイルから名前と価格を読み取れるようにするコードを教えてくれるか、助けてくれる人が必要です。

これは私がすでに持っているものです。

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

また、テキスト文書から読み取る行を選択する方法も素晴らしいでしょう。

4

3 に答える 3

10

テキスト ファイルの形式を教えてくれませんでした。私は次のことを前提としています。

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

出力も指定しませんでした。私は次のことを前提としています。

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

次に、以下はそのようなファイルを読み取り、目的の出力を生成します。

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)
        );
    }
}

セパレーターが異なる場合は、パラメーター'|'をメソッドに変更する必要があります ( named asString.Splitのインスタンスで呼び出されます)。Stringlineline.Split('|')

フォーマットを変える必要がある場合は、ラインで遊ぶ必要があります

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

ご不明な点がございましたら、お知らせください。

于 2010-01-14T22:16:35.317 に答える
0

http://www.blackbeltcoder.com/Articles/strings/a-text-parsing-helper-classで説明されているような解析ヘルパー クラスを開始点として使用することもできます。

于 2010-12-23T18:43:02.357 に答える
0
    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);
        }

@Jason の方法と同じ結果が得られますが、これは最適化されたバージョンだと思います。

于 2010-01-14T23:15:35.760 に答える