How can I convert a string with newlines in it to separate lines?

前端 未结 5 505
感情败类
感情败类 2021-01-23 21:46

How to convert string that have \\r\\n to lines?

For example, take this string:

string source = \"hello \\r\\n this is a test \\r\\n tested\         


        
5条回答
  •  野性不改
    2021-01-23 22:37

    Use String.Split Method (String[], StringSplitOptions) like this:

    var lines = source.Split(new [] { "\r\n", "\n" }, StringSplitOptions.None);
    

    This one will work regardless of whether the source is written with Windows linebreak \r\n or Unix \n.

    As other answers mention, you could use StringSplitOptions.RemoveEmptyEntries instead of StringSplitOptions.None which, as the name says, removes empty strings (" " does not qualify for being empty, only ""does).

提交回复
热议问题