通過正則表達式 Regex.Replace() 和匹配符 \s(匹配任何空白字符,包括空格、制表符、換頁符等,與[\f\n\t\r\v]等效),代碼如下:
using System; using System.Text.RegularExpressions; namespace Test { class Program { static void Main(string[] args) { string testStr = " this\n is\r a \ttest "; Console.WriteLine(Regex.Replace(testStr, @"\s", "")); Console.Read(); } } }
運行結果如下: