开发者

How to split lines from Windows text file (/r/n separation)

My question is quite simple. I need to get all text lines from Windows text file. All lines are separated by \r\n symbols. I use String.Split, but its not cool, because it only splits 'by one symbol' leaving empty string that I need to remove with options flag. Is there a better way?

My implementat开发者_Python百科ion

string wholefile = GetFromSomeWhere();

// now parsing
string[] lines = operationtext.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

// ok now I have lines array

UPDATE

File.ReadAllXXX is of no use here coz GetFromSomeWhere is actually RegEx, so I've no file after this point.


You can use this overload of String.Split, which takes an array of strings that can serve as delimiters:

string[] lines = operationtext.Split(new[] { Environment.NewLine },  
                                     StringSplitOptions.RemoveEmptyEntries);

Of course, if you already have the file-path, it's much simpler to use File.ReadAllLines:

string[] lines = File.ReadAllLines(filePath);


String.Split does accept a string (like "\r\n"). Not just a chararray.

string[] lines = wholetext.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);


You may find it much easier to simply use File.ReadAllLines() or File.ReadLines()


you could use an extension method like the one below and your code would then look like this:

    var lines = operationText.ReadAsLines();

Extension method implementation:

    public static IEnumerable<string> ReadAsLines(this string text)
    {
        TextReader reader = new StringReader(text);
        while(reader.Peek() >= 0)
        {
            yield return reader.ReadLine();
        }
    }

I'm guessing it's not as performant as the split option which is usually very performant but if that's not an issue...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜