首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 高效去除字符串中的換行符與回車符

     編輯:關於C#

一、問題背景

在處理文本數據時,常需移除字符串中的換行符(`\n`, ASCII 10)與回車符(`\r`, ASCII 13)。例如讀取多行文本框內容、解析文件、清理用戶輸入等場景。

二、核心方法:StreamReader 配合 Replace

利用 StreamReader 讀取完整文本,再鏈式調用 Replace 移除控制字符:

StreamReader sr = new StreamReader(this.textBox1.Text, System.Text.Encoding.Default);
this.textBox2.Text = sr.ReadToEnd()
    .Replace((char)10, '')  // 移除換行符 \n
    .Replace((char)13, ''); // 移除回車符 \r
this.textBox2.SelectAll();
sr.Close();

三、更通用的擴展方法(推薦)

封裝為字符串擴展方法,隨處可用:

public static class StringExtensions {
    /// 
    /// 移除所有換行符、回車符及其組合(\r\n, \n, \r)
    /// 
    public static string RemoveNewLines(this string input) {
        if (string.IsNullOrEmpty(input)) return input;
        return input.Replace("\r\n", "").Replace("\n", "").Replace("\r", "");
    }
    
    /// 
    /// 替換為單個空格,保持單詞分隔
    /// 
    public static string NormalizeNewLines(this string input, string replacement = " ") {
        if (string.IsNullOrEmpty(input)) return input;
        return System.Text.RegularExpressions.Regex.Replace(input, @"\r\n|\n|\r", replacement);
    }
}

使用示例:

string cleanText = dirtyText.RemoveNewLines();
// 或保留單詞間隔
string normalized = dirtyText.NormalizeNewLines(" ");

四、性能優化建議

  • 大文本:使用 StringBuilder 逐字符處理,避免多次分配新字符串。
  • 高頻調用:預編譯正則表達式(`RegexOptions.Compiled`)。
  • 僅需移除:鏈式 Replace 最簡潔高效。

五、常見編碼陷阱

  1. 僅替換 `\n` 而遺漏 `\r`(Mac 經典格式)或 `\r\n`(Windows 格式)。
  2. 直接修改原字符串引用而未重新賦值(字符串不可變)。
  3. 未指定編碼讀取文件導致亂碼,建議顯式指定 `Encoding.UTF8` 或 `Encoding.Default`。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved