Thursday, February 19, 2009

How To Split Java String By Newlines



Splitting a String by newline is a common requirement. When processing textual data from files or from web we need to split the data by newline boundaries. The solution aren't hard either. Let's see a simple one liner solution using String.split().

String[] poList = pos.split("\r\n|\r|\n");

What did I do?
I am splitting the String based on a regular expression which looks for carriage return (\r) or line feed (\n) or carriage return immediately followed by line feed. These takes care of all types of newlines you may encounter. It returns, as you can see, a String array of results. Trailing empty strings are not included in the resulting array.

What's interesting?
The following will include a whole bunch of empty Strings in the result.
String[] poList = pos.split("\r|\n|\r\n");

Can you tell why?
How many alternatives can you tell like using StringTokenizer for example?

No comments: