Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

แทนที่ Line Breaks ใน String ใน C#

กำจัด Newline (\n), Carriage Return (\r), Tab (\t) จาก String

1. ใช้ String.Replace()

string input = "Hello \n\r beautiful \n\t world";
string result = input.Replace("\n\r", "_").Replace("\n\t", "_");
// "Hello _ beautiful _ world"

ต้อง Replace ทีละ Pattern

2. ใช้ Regex.Replace() (แนะนำ)

using System.Text.RegularExpressions;

string input = "Hello \n\r beautiful \n\t world";
string result = Regex.Replace(input, @"\n\r|\n\t", "_");
// "Hello _ beautiful _ world"

Regex รองรับหลาย Pattern พร้อมกัน (| = OR) และ \s ครอบคลุม Whitespace ทุกชนิด

Regex Pattern ที่น่าสนใจ

  • \r\n|\r|\n → ทุก Newline Style (Windows/Mac/Linux)
  • \s+ → Whitespace ทุกชนิด (Space, Tab, Newline)