How to remove new line characters from a string?

后端 未结 11 979
时光取名叫无心
时光取名叫无心 2020-11-27 10:32

I have a string in the following format

string s = \"This is a Test String.\\n   This is a next line.\\t This is a tab.\\n\'

I want to remo

11条回答
  •  盖世英雄少女心
    2020-11-27 11:25

    The right choice really depends on how big the input string is and what the perforce and memory requirement are, but I would use a regular expression like

    string result = Regex.Replace(s, @"\r\n?|\n|\t", String.Empty);
    

    Or if we need to apply the same replacement multiple times, it is better to use a compiled version for the Regex like

    var regex = new Regex(@"\r\n?|\n|\t", RegexOptions.Compiled); 
    string result = regex.Replace(s, String.Empty);
    

    NOTE: different scenarios requite different approaches to achieve the best performance and the minimum memory consumption

提交回复
热议问题