当前位置:   article > 正文

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

c# word 分页保存 text

最近做一个VR项目,需要把某个中草药的介绍信息分页显示到unity场景里然后用VR手柄切换信息。

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

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

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

下面是控制台测试效果:

txt文本:

 

处理效果:

下面是代码:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.IO;
  7. namespace ConsoleFileTest
  8. {
  9. class Program
  10. {
  11. static void Main(string[] args)
  12. {
  13. int totalPage; //这个值是总页数
  14. string[] pageInformation = getPageInfo("E:\\test.txt",out totalPage); //得到的每页信息的数组
  15. Console.WriteLine("返回的介绍信息有" + totalPage + "页\n");
  16. //遍历所有页并显示信息
  17. for(int i = 0; i < totalPage; i++)
  18. {
  19. Console.WriteLine("第" + i + "页:\n" + pageInformation[i]);
  20. }
  21. Console.Read();
  22. }
  23. static string[] getPageInfo(string pathRoot, out int pageNum)
  24. {
  25. string[] intro = new string[30]; //每行字符存储的数组
  26. string[] pageInfo = new string[30]; //每页信息的数组,默认不超过30页。
  27. int max_char_for_a_line = 15; //每行最多存储的字符个数
  28. int max_line_for_a_page = 6; //每页最多存储的行数
  29. string str = File.ReadAllText(pathRoot, Encoding.Default); //读取文件赋给一个string
  30. int length = str.Length; //文件里字符串总长度
  31. int correntLine = 0; //当前行数
  32. int tempChar = 0; //当前行字符个数
  33. for (int i = 0; i < length; i++)
  34. {
  35. if ((str[i] != '\n') && (str[i] != '\r'))
  36. {
  37. if (tempChar == max_char_for_a_line) //如果已经存了15个字符就换行
  38. {
  39. correntLine++;
  40. tempChar = 0;
  41. }
  42. tempChar++;
  43. intro[correntLine] += str[i];
  44. }
  45. else if (str[i] == '\n')
  46. {
  47. tempChar = 0;
  48. correntLine++;
  49. }
  50. }
  51. int totalLine = correntLine + 1;
  52. //现在intro[]为分行数组,totalLine为总行数
  53. int correntPage = 0; //当前第几页
  54. int correntPageLine = 0; //当前页到几行
  55. for (int i = 0; i < totalLine; i++)
  56. {
  57. if (correntPageLine == max_line_for_a_page) //到了最大行就换一页
  58. {
  59. correntPage++;
  60. correntPageLine = 0;
  61. }
  62. pageInfo[correntPage] = pageInfo[correntPage] + intro[i] + "\n";
  63. correntPageLine++;
  64. }
  65. pageNum = correntPage + 1; //out出总页数
  66. return pageInfo; //返回每页信息的数组
  67. }
  68. }
  69. }

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

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

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

 

转载于:https://www.cnblogs.com/dhx96/p/7099555.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/391383
推荐阅读
相关标签
  

闽ICP备14008679号