How To Split Java String By Newlines

By Angsuman Chakraborty, Gaea News Network
Thursday, July 19, 2007

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

Discussion

P
March 4, 2010: 5:24 am

why not use the \s delimeter. It is predifined to mean: [ \t\n\x0B\f\r].
Thus, any whitespace character.

So:
String[] poList = pos.split(”\\s”);


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:
Unless the user presses the enter key i want to get substrings(texts) of 15 characters each or else whenever the user presses enter i want to seperate that part out and start again counting till 15 to get a new splittted substring till i reach the end of the free flow text/string.
Eg,
If user enters:

Heloo i want
enter key to be caught.

So i want this text to be seperated into the below substrings:
1. Hello i want(assuming the user pressed enter key at this point)
2. enter key to be(as the limit is 15)
3. caught


arun
December 23, 2008: 12:06 pm

can anyone please tell me how to split the string
String s =”$KL8G4391,061208,1130002,17266724N,0765423E,002,273#”;
without the $ or the # sign appearing.


Johan Avén
January 22, 2008: 12:54 am

Answer to #3
To split a string around periods (.), use …

a.split("\\.")


vijayvarma
November 27, 2007: 8:43 am

Hi

Can any one provide the solution for this

String a = “10.00″;
String result[] = a.split(”.”);
for(String value[] : result)
{
System.out.printl(value[0].toString());
}

But in this case the output is not reaching the for loop
Can anyone provide the solution for this.

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.


Jay
July 20, 2007: 1:07 pm

Since “\r” is first, “\r\n” is never found.

YOUR VIEW POINT
NAME : (REQUIRED)
MAIL : (REQUIRED)
will not be displayed
WEBSITE : (OPTIONAL)
YOUR
COMMENT :