c#讀取文本文檔實踐1-File.ReadAllLines()


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace 書名總價格計算
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = @"C:\Users\Administrator\Desktop\書名總價格計算.txt";
            string[] contents = File.ReadAllLines(path, Encoding.Default);
            for (int i = 0; i < contents.Length; i++)
            {
                string[] strNew = contents[i].Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                Console.WriteLine("{0} {1} {2}", strNew[0], strNew[1], strNew[2]);
            }
        }
    }
}

 上述代碼可以切分文本文檔中空格或制表符分隔,比如下圖文本文檔, 

都可以輸出到控制台。

 


上述代碼中用到File.ReadAllLines()函數,適用於讀取較小的文本文檔,一次性將全部文本文檔內容放入字符串數組contents中,每一行作為contents這個字符串數組的一個元素,下面的循環實現了對contents的遍歷,遍歷的過程中通過split函數對每個元素按空格或者是制表符進行分割,contents的每個元素被按照空格或制表符分割后返回一個新的字符串數組,放入到新定義的strNew這個字符串數組中,之后輸出。

下一步要計算總價格。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM