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