How to remove new line characters from a string?

后端 未结 11 916
时光取名叫无心
时光取名叫无心 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:23

    A LINQ approach:

    string s = "This is a Test String.\n   This is a next line.\t This is a tab.\n'";
    
    string s1 = String.Join("", s.Where(c => c != '\n' && c != '\r' && c != '\t'));
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-27 11:25
    string remove = Regex.Replace(txtsp.Value).ToUpper(), @"\t|\n|\r", "");
    
    0 讨论(0)
  • 2020-11-27 11:26

    I like to use regular expressions. In this case you could do:

    string replacement = Regex.Replace(s, @"\t|\n|\r", "");
    

    Regular expressions aren't as popular in the .NET world as they are in the dynamic languages, but they provide a lot of power to manipulate strings.

    0 讨论(0)
  • 2020-11-27 11:26

    Well... I would like you to understand more specific areas of space. \t is actually assorted as a horizontal space, not a vertical space. (test out inserting \t in Notepad)

    If you use Java, simply use \v. See the reference below.

    \h - A horizontal whitespace character:

    [\t\xA0\u1680\u180e\u2000-\u200a\u202f\u205f\u3000]

    \v - A vertical whitespace character:

    [\n\x0B\f\r\x85\u2028\u2029]

    But I am aware that you use .NET. So my answer to replacing every vertical space is..

    string replacement = Regex.Replace(s, @"[\n\u000B\u000C\r\u0085\u2028\u2029]", "");
    
    0 讨论(0)
提交回复
热议问题