如何通过行终止符("\ r \ n")将长字符串快速拆分为子字符串? [英] How can I quickly split a long string into serval ones by the line terminator ("\r\n")?
问题描述
在C#代码中,是否有一种简单的方法可以通过行终止符("\ r \ n")将长字符串拆分为serval?
感谢
Is there a simple way to split a long string into servals by the line terminator ("\r\n") in C# code?
Thanks
推荐答案
string bla = "abc\r\ndef\r\nghijk";
string [] splitter = { "\r\n" };
string [] foo = bla.Split(splitter, StringSplitOptions.RemoveEmptyEntries);
或使用Streams,可能会从文件中获取此字符串.但这仅在您具有CR/LF分离器"的情况下有效.
or with Streams, probably you get this string out of a file. But this only works in cases where you habe CR/LF "Splitters".
string bla = "abc\r\ndef\r\nghijk";
using (StringReader sr = new StringReader(bla))
{
string line = string.Empty;
do
{
line = sr.ReadLine();
if (line != null)
{
Debug.WriteLine(line);
}
} while (line != null);
}
这有帮助吗?
Does this help?
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string value = "cat\r\ndog\r\nanimal\r\nperson";
//
// Split the string on line breaks.
// ... The return value from Split is a string[] array.
//
string[] lines = Regex.Split(value, "\r\n");
foreach (string line in lines)
{
Console.WriteLine(line);
}
}
}
也请检查此页面:
http://www.dotnetperls.com/split [
Also check this page out:
http://www.dotnetperls.com/split[^]
Cheers
解决方案2很好.
但是,如果有空白,我认为它们可能不会被删除.
The Solution 2 is very good.
But, if there are empty spaces, I think they may not be deleted.
void Main()
{
string input= "First Line\r\nSecond Line\r\n\r\nThird Line";
string[] lines = input.Split(new string[]{"\r\n"},
StringSplitOptions.RemoveEmptyEntries);
foreach (string line in lines)
{
Console.WriteLine (line);
}
}
//First Line
//Second Line
//Third Line
在上面显示的示例中,在SecondLine之后,由于\ r \ n的替换,因此有一个空条目.使用StringSplitOptions.RemoveEmptyEntries选项可以删除此空条目.
In the sample shown above after SecondLine there is an empty entry due to repition of \r\n. With StringSplitOptions.RemoveEmptyEntries option this empty entry can removed.
这篇关于如何通过行终止符("\ r \ n")将长字符串快速拆分为子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!