C#简单实现读取txt文本文件并分页存储到数组

来源:互联网 发布:autocad2008软件下载 编辑:程序博客网 时间:2024/06/08 05:56
最近做一个VR项目,需要把某个中草药的介绍信息分页显示到unity场景里然后用VR手柄切换信息。

unity的脚本是c#,就先在本地写了个代码测试了一下,利用控制台测试输出,到时候拷贝函数过去再结合交互就可以实现处理了。

可以自由设定每行要显示的字符数和每页要显示的行数。

函数返回每一页信息的string数组,和总页数两个参数。

下面是控制台测试效果:

txt文本:

 

处理效果:

下面是代码:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.IO;namespace ConsoleFileTest{        class Program    {               static void Main(string[] args)        {                        int totalPage; //这个值是总页数            string[] pageInformation = getPageInfo("E:\\test.txt",out totalPage); //得到的每页信息的数组            Console.WriteLine("返回的介绍信息有" + totalPage + "页\n");            //遍历所有页并显示信息            for(int i = 0; i < totalPage; i++)            {                Console.WriteLine("第" + i + "页:\n" + pageInformation[i]);            }                  Console.Read();        }               static string[] getPageInfo(string pathRoot, out int pageNum)        {                    string[] intro = new string[30]; //每行字符存储的数组            string[] pageInfo = new string[30]; //每页信息的数组,默认不超过30页。            int max_char_for_a_line = 15; //每行最多存储的字符个数            int max_line_for_a_page = 6; //每页最多存储的行数                        string str = File.ReadAllText(pathRoot, Encoding.Default); //读取文件赋给一个string            int length = str.Length; //文件里字符串总长度                int correntLine = 0; //当前行数            int tempChar = 0; //当前行字符个数            for (int i = 0; i < length; i++)            {                if ((str[i] != '\n') && (str[i] != '\r'))                {                    if (tempChar == max_char_for_a_line) //如果已经存了15个字符就换行                    {                        correntLine++;                        tempChar = 0;                    }                    tempChar++;                    intro[correntLine] += str[i];                }                else if (str[i] == '\n')                {                    tempChar = 0;                    correntLine++;                }            }            int totalLine = correntLine + 1;            //现在intro[]为分行数组,totalLine为总行数            int correntPage = 0; //当前第几页            int correntPageLine = 0; //当前页到几行            for (int i = 0; i < totalLine; i++)            {                if (correntPageLine == max_line_for_a_page) //到了最大行就换一页                {                    correntPage++;                    correntPageLine = 0;                }                pageInfo[correntPage] = pageInfo[correntPage] + intro[i] + "\n";                correntPageLine++;            }                                 pageNum = correntPage + 1; //out出总页数            return pageInfo; //返回每页信息的数组        }            }}

比较无脑的实现,没什么高端算法。要注意的是,如果一个函数需要返回两个参数就需要用到out关键字,我这里一个是函数本身的返回值(为string类型的数组),还有一个是out出来的总页数值,这个需要在外部先定义然后获取。

另外一点是windows文本文档,在换行的时候默认是加入了两个字符的,分别为"\r"回车符和"\n"换行符,占了两个位置,处理的时候也需要注意。

写这篇博客的目的是想告诉自己,一定要多动脑,要不然脑子会生锈。

 

阅读全文
0 0
原创粉丝点击