如何将具有\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 ;
如何将具有\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 linebreak \r\n
或Unix编写\n
。
至于其他的答案中提到,您可以使用StringSplitOptions.RemoveEmptyEntries
代替StringSplitOptions.None
,正如它的名字说,删除空字符串(" "
没有资格为空,只有""
一样)。
尝试
string[] items = source.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
他没有声明他想删除空条目。 – 2010-08-23 08:35:58
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);
}
可以使用overloads of System.String.Split使用单个字符,字符数组,或字符串值的数组作为分隔符用于拆分字符串。 StringSplitOptions指定是否保留空行或删除它们。 (例如,如果要分割多行文本(如段落,但会在名称列表的示例中删除它们),则会希望保留它们)
除了提到的string.Split,您也可以使用Regex.Split,但对于更复杂的分割模式通常更有用。
var lines = Regex.Split(source, @"\r\n");
我会说正则表达式会是更好的解决方案;如果您还想删除换行符之前和之后的空格,或者没有回车符。正则表达式会是这样的:@“* \ r?\ n *” – 2010-08-23 09:43:29
@Andre:我同意当你不是100%确定的输入。然后你可以用正则表达式更好的模糊分割。如果您自己创建文件,则可能不需要。 – 2010-08-23 10:52:53
为了清楚起见,我做了另一个答案。
我做了这两种扩展方法:
ReadLines
将让你阅读的时候一行没有整个字符串解析到一个数组。 ReadAllLines
会将整行解析为一个数组。
在你的情况,你可以用它喜欢:
var lines = source.ReadAllLines();
我从File.ReadLines
和File.ReadAllLines
采取的名称,以便它们应与.NET Framework的其余部分保持一致。
作为一个侧面说明,以我的其他答案的评论,我已经检查StringReader.ReadLine
的代码,这也同时兼顾\r\n
和\n
的 - 而不是旧的遗留MAC OS等(不应该是很重要的)。
public static class StringExtensions
{
public static IEnumerable<string> 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<string>();
using (var sr = new StringReader(data))
{
string line;
while ((line = sr.ReadLine()) != null)
res.Add(line);
}
return res.ToArray();
}
}
(ReadAllLines
可能已与ReadLines.ToArray
,但我决定,额外的代码行数比一个包裹IEnumerable
这需要一些处理时间更好)
您可以添加的Mac:'\ r'为以及IBM的'\ x0085'(请参阅[本说明](http://www.w3.org/TR/newline)):) – Abel 2010-08-23 08:38:53
不知道他们有'\ r',但我只看到' Mac OS <= 9',因此它们正确无关。 – 2010-08-23 08:41:44
正确的常量是System.Environment.NewLine。 – 2010-08-23 08:50:50