Skip to main content
 首页 » 编程设计

c#之如何将其中包含换行符的字符串转换为单独的行

2024年02月24日32mengfanrong

如何将包含\r\n的字符串转为行?

例如,取这个字符串:

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

以及如何将其转换为:

string[] lines ; 
 
//lines[0] = hello; 
//lines[1] = this is a test; 
//lines[2] = tested ; 

请您参考如下方法:

使用String.Split Method (String[], StringSplitOptions)像这样:

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

无论源代码是用 Windows 换行符 \r\n 还是 Unix \n 编写的,这个都可以工作。

正如其他答案提到的,您可以使用 StringSplitOptions.RemoveEmptyEntries 而不是 StringSplitOptions.None ,顾名思义,它会删除空字符串 ("" 不符合为空的条件,只有 "" 符合)。