Normalize newlines in C#

前端 未结 8 2033
滥情空心
滥情空心 2020-12-03 06:48

I have a data stream that may contain \\r, \\n, \\r\\n, \\n\\r or any combination of them. Is there a simple way to normalize the data to make all of them simply become \\r

相关标签:
8条回答
  • 2020-12-03 07:25

    It's a two step process.
    First you convert all the combinations of \r and \n into a single one, say \r
    Then you convert all the \r into your target \r\n

    normalized = 
        original.Replace("\r\n", "\r").
                 Replace("\n\r", "\r").
                 Replace("\n", "\r").
                 Replace("\r", "\r\n"); // last step
    
    0 讨论(0)
  • I agree Regex is the answer, however, everyone else fails to mention Unicode line separators. Those (and their variations with \n) should be included.

    0 讨论(0)
提交回复
热议问题