How to split a string while preserving line endings?

后端 未结 6 1264
谎友^
谎友^ 2021-01-01 06:02

I have a block of text and I want to get its lines without losing the \\r and \\n at the end. Right now, I have the following (suboptimal code):

<         


        
6条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-01 06:42

    If you are just going to replace the newline (\n) then do something like this:

    string[] lines = tbIn.Text.Split('\n')
                         .Select(t => t + "\r\n").ToArray();
    

    Edit: Regex.Replace allows you to split on a string.

    string[] lines = Regex.Split(tbIn.Text, "\r\n")
                 .Select(t => t + "\r\n").ToArray();
    

提交回复
热议问题