alain.janinm alain.janinm - 7 months ago 13
Java Question

What is the best way to iterate over the lines of a Java String?

Currently I'm using something like :

String[]lines = textContent.split(System.getProperty("line.separator"));
for(String tmpLine : lines){
//do something
}


I'm not very glad of this method because it create an heavy array (let say
textContent
can contain a book).

Is there any better solution to iterate over the lines of a
String
?

Answer

You could use :

BufferedReader bufReader = new BufferedReader(new StringReader(textContent));

And use the readLine() method :

String line=null;
while( (line=bufReader.readLine()) != null )
{

}
Comments