如何使用.Split()在空行上分割字符串?

16
为了完成一项课程项目,我需要将一个文本文件加载到一个链表中。 目前为止,我能够从文件中读取数据,但是我无法将其分成部分以便将其放入链表中。
例如,我希望在空行处将这些项拆分开来: David Hunter No1 Admin
John Smith No11 Sales
Jane Appleby No5 Accounts
我尝试了String [] people = record.Split('\ n'); 但是这只是在每一行处拆分它。
我还尝试过: String [] people = record.Split('\ n \ r'); String [] people = record.Split('\ r \ n'); String [] people = record.Split('\ n \ n'); 但是由于“字符文字中的字符太多”,它无法编译。
请问有没有人能建议一种方法来完成这个任务(最好不使用正则表达式)?

请向我们展示如何“读取获取文件”。 - Dour High Arch
3
"\r\n\r\n"处分割 - 注意要用双引号表示字符串而非单引号表示字符。 - Blorgbeard
2
txt.Split(new string[] { Environment.NewLine + Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries) - Sky Fang
@SkyFang 为什么要使用 Environment.NewLine + Environment.NewLine?我认为 record.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries) 就足够了。 - Mick
1
@Mick 在任何 "\r\n"、"\r" 或 "\n" 处都会断开。OP 想要在空行上断开,即两个连续的换行符 ("\r\n\r\n")。 - Fernando Matsumoto
显示剩余6条评论
1个回答

31
您可以使用

来完成它。

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

它所做的是使用StringSplitOptions.RemoveEmptyEntries删除空条目,然后在相邻两个换行符之后进行分割。


1
这个可行,谢谢!同时也非常感谢其他提供帮助的人! - gcstudent

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接