String.Replace也是全部替換。
如果您需要替換復雜的內容,可以使用正則表達式。
正則對復雜字串的替換效率高。C#中的正則表達式默認貪婪算法,總試圖匹配更多的字符,所以若是簡單的替換一個或幾個字符,還是不要用比較好。
Regex.Replace()
需要引用System.Text.RegularExpression命名空間。
C# String 正則 替換空格 tab字符 換行符 新行
使用正則表達式匹配符"\s",它將匹配任何空格包含在這個字符串里C#空格, tab字符, 換行符和新行(newline).
string trim = Regex.Replace( text, @"\s", "");
例:c# 字符串多個TAB 替換成1個TAB
string trim = Regex.Replace("system threading_ thread_ currentthread _currentculture_textinfo", @"\t\t", "\t");
輸出結果:
system threading_ thread_ currentthread _currentculture_textinfo