Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read String Builder line by line

Tags:

Can I read String Builder line by line? And Get the length of each line as well.


EDIT:

"I build string in StringBuilder and add "\n" within. And I need to read it again. I need to consider that every "\n" has a new line."

like image 243
Ran Gualberto Avatar asked Aug 25 '11 12:08

Ran Gualberto


People also ask

How do you read each line in a string?

BufferedReader reader = new BufferedReader(new StringReader(<string>)); reader. readLine(); Another way would be to take the substring on the eol: final String eol = System.

How does a string builder work?

The StringBuilder works by maintaining a buffer of characters (Char) that will form the final string. Characters can be appended, removed and manipulated via the StringBuilder, with the modifications being reflected by updating the character buffer accordingly. An array is used for this character buffer.

Can you compare string to StringBuilder?

We can use the equals() method for comparing two strings in Java since the String class overrides the equals() method of the Object class, while StringBuilder doesn't override the equals() method of the Object class and hence equals() method cannot be used to compare two StringBuilder objects.


1 Answers

Given your edit, it's as simple as invoking toString() on the StringBuilder instance, and then invoking split("\\n") on the returned String instance. And from there, you'll have a String array that you can loop through to access each "line" of the StringBuilder instance. And of course, invoke length() on each String instance, or "line" to get its length.


StringBuilder sb = new StringBuilder(); sb.append("line 1"); sb.append("\\n"); sb.append("line 2");  String[] lines = sb.toString().split("\\n"); for(String s: lines){     System.out.println("Content = " + s);     System.out.println("Length = " + s.length()); } 
like image 87
mre Avatar answered Sep 29 '22 16:09

mre