去除文本多余空行
Posted 贝尔格里尔斯
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了去除文本多余空行相关的知识,希望对你有一定的参考价值。
1.读取文件:
OpenFileDialog dialog=new OpenFileDialog(); dialog.InitialDirectory = Application.StartupPath; dialog.Filter = "All Files|*.*|text file(*.txt)|*.txt"; dialog.RestoreDirectory = true; if (dialog.ShowDialog() == DialogResult.OK) { string filepath = dialog.FileName.ToString(); string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1); textBox1.Text = filepath; using (StreamReader sr = new StreamReader(filepath, Encoding.Default))//如果乱码,可改为System.Text.Encoding.UTF-8;或者System.Text.Encoding.GBK { string str; string line=""; while ((str = sr.ReadLine()) != null) { line+=str+"\n"; } richTextBox1.Text = line; } }
注:通过拖拽文件打开文件:
private void Form1_DragEnter(object sender, DragEventArgs e) { string path = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString(); textBox1.Text = path; //将获取到的完整路径赋值到textBox1 using (StreamReader sr = new StreamReader(path, Encoding.Default))//如果乱码,可改为System.Text.Encoding.UTF-8;或者System.Text.Encoding.GBK { string str; string line = ""; while ((str = sr.ReadLine()) != null) { line += str + "\n"; } richTextBox1.Text = line; } }
2.去除空行:
richTextBox1.Clear(); string[] xynet = File.ReadAllLines(textBox1.Text, Encoding.Default); for (int i = 0; i < xynet.Length; i++) { if (xynet[i].Trim() == "") { } else { richTextBox1.Text+= xynet[i]+"\n"; } }
3.保存:
if (this.richTextBox1.Text == "") return; SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.DefaultExt = "txt"; saveFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*"; if (saveFileDialog1.ShowDialog() == DialogResult.Cancel) return; string FileName = saveFileDialog1.FileName; richTextBox1.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.PlainText);
4.清空:
textBox1.Text = string.Empty; richTextBox1.Text = string.Empty;
以上是关于去除文本多余空行的主要内容,如果未能解决你的问题,请参考以下文章
华为OD机试真题Java实现去除多余空格真题+解题思路+代码(2022&2023)