在處理文本數據時,常需移除字符串中的換行符(`\n`, ASCII 10)與回車符(`\r`, ASCII 13)。例如讀取多行文本框內容、解析文件、清理用戶輸入等場景。
利用 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 逐字符處理,避免多次分配新字符串。Replace 最簡潔高效。