How do I split a string on an empty line using .Split()?

有些话、适合烂在心里 提交于 2019-12-23 09:21:34

问题


For a class project I have to load a text file into a linked list. So far, I have been able to read from the file, but I am struggling to split it up into sections so that I can put it into the linked list.

For example, I would like to split these items up at the empty lines:

David
Hunter
No1
Admin

John
Smith
No11
Sales

Jane
Appleby
No5
Accounts

I have tried String[] people = record.Split('\n'); but of course, this just splits it at every line.

I have also tried:
String[] people = record.Split('\n\r');
String[] people = record.Split('\r\n');
String[] people = record.Split('\n\n');
but it won't compile due to "too many characters in character literal"

Could anyone please suggest a way to do this (preferably without regex)?


回答1:


You can get it accomplished by using

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

or

string[] people = record.Split(new string[] { Environment.NewLine + Environment.NewLine },
                               StringSplitOptions.RemoveEmptyEntries);

What it does is it removes empty entries with StringSplitOptions.RemoveEmptyEntries and then splits where two linebreaks are right after each other.



来源:https://stackoverflow.com/questions/32429967/how-do-i-split-a-string-on-an-empty-line-using-split

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!