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."
BufferedReader reader = new BufferedReader(new StringReader(<string>)); reader. readLine(); Another way would be to take the substring on the eol: final String eol = System.
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.
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.
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()); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With