如何将带有换行符的字符串转换为单独的行?
如何将\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方法(String [],StringSplitOptions),如下所示:
var lines = source.Split(new [] { "\r\n", "\n" }, StringSplitOptions.None);
无论源是使用Windows linebreak \r\n
还是Unix \n
编写,这个都可以使用。
正如其他答案所提到的,您可以使用StringSplitOptions.RemoveEmptyEntries
而不是StringSplitOptions.None
,正如名称所示,它删除空字符串( " "
不符合空,只有""
确实如此)。
除了提到的string.Split之外,您还可以使用Regex.Split ,但它通常对更复杂的分割模式更有用。
var lines = Regex.Split( source, @"\r\n" );
string text = "Hello \r\n this is a test \r\n tested"; string[] lines = text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); foreach (string line in lines) { System.Diagnostics.Debug.WriteLine(line); }
您可以使用System.String.Split的重载来使用单个字符,字符数组或字符串值数组作为拆分字符串的分隔符。 StringSplitOptions指定是否保留空行或删除它们。 (例如,如果要分割多行文本(如段落),则会保留它们,但会在名称列表的示例中将其删除)
尝试
string[] items = source.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
为清楚起见,我做了另一个答案。
我做了这两个扩展方法:
ReadLines
将允许您在不将整个字符串解析为数组的情况下读取一行。 ReadAllLines
将整行解析为数组。
在您的情况下,您可以使用它:
var lines = source.ReadAllLines();
我从File.ReadLines
和File.ReadAllLines
获取了名称,因此它们应与.Net框架的其余部分保持一致。
作为对我的另一个答案的评论的旁注,我检查了StringReader.ReadLine
的代码,这确实处理了\r\n
和\n
– 但不是旧的旧Mac OS等(不应该重要) )。
public static class StringExtensions { public static IEnumerable ReadLines(this string data) { using (var sr = new StringReader(data)) { string line; while ((line = sr.ReadLine()) != null) yield return line; } } public static string[] ReadAllLines(this string data) { var res = new List (); using (var sr = new StringReader(data)) { string line; while ((line = sr.ReadLine()) != null) res.Add(line); } return res.ToArray(); } }
( ReadAllLines
可以使用ReadLines.ToArray
制作,但我认为额外的几行代码比包装的IEnumerable
更好,这需要一些处理时间)