C#简单实现读取txt文本文件并分页存储到数组
生活随笔
收集整理的這篇文章主要介紹了
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"換行符,占了兩個位置,處理的時候也需要注意。
寫這篇博客的目的是想告訴自己,一定要多動腦,要不然腦子會生銹。
?
轉載于:https://www.cnblogs.com/dhx96/p/7099555.html
總結
以上是生活随笔為你收集整理的C#简单实现读取txt文本文件并分页存储到数组的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: WEB测试基础
- 下一篇: c# char unsigned_dll