How To Split Java String By Newlines
By Angsuman Chakraborty, Gaea News NetworkThursday, July 19, 2007
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?
March 4, 2010: 5:24 am
why not use the \s delimeter. It is predifined to mean: [ \t\n\x0B\f\r]. So: |
![]() desmiserables |
June 20, 2009: 6:56 pm
i have a textarea where a user can enter free flow text.I want to seperate out lines/occurences in my java class based on the below conditions: Heloo i want So i want this text to be seperated into the below substrings: |
![]() arun |
December 23, 2008: 12:06 pm
can anyone please tell me how to split the string |
![]() Johan Avén |
![]() vijayvarma |
November 27, 2007: 8:43 am
Hi Can any one provide the solution for this String a = “10.00″; But in this case the output is not reaching the for loop |
July 21, 2007: 1:54 am
Which is why the \r and \n of a “\r\n” are treated separately and an empty line is assumed in between them. |
P