Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)?

like image 704
gcstudent Avatar asked Sep 07 '15 01:09

gcstudent


People also ask

How do you split text in new line?

To split a string by newline, call the split() method passing it the following regular expression as parameter - /\r?\ n/ . The split method will split the string on each occurrence of a newline character and return an array containing the substrings. Copied!

How do I split a string into string?

Use the Split method when the substrings you want are separated by a known delimiting character (or characters). Regular expressions are useful when the string conforms to a fixed pattern. Use the IndexOf and Substring methods in conjunction when you don't want to extract all of the substrings in a string.

How do I split a string in Visual Studio?

Split(String[], Int32, StringSplitOptions) Method This method is used to splits a string into a maximum number of substrings based on the strings in an array. You can specify whether the substrings include empty array elements. Syntax: public String[] Split(String[] separator, int count, StringSplitOptions options);

How do I split a string into another character?

You can use String. Split() method with params char[] ; Returns a string array that contains the substrings in this instance that are delimited by elements of a specified Unicode character array.


1 Answers

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.

like image 172
Mohit S Avatar answered Sep 23 '22 17:09

Mohit S