失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > C#简单实现读取txt文本文件并分页存储到数组

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

时间:2021-09-26 01:08:27

相关推荐

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

最近做一个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); //读取文件赋给一个stringint 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"换行符,占了两个位置,处理的时候也需要注意。

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

如果觉得《C#简单实现读取txt文本文件并分页存储到数组》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。