Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Standard way to iterate over a StringBuilder in Java?

I was quite surprised that I couldn't find an existing questions answering this.

What is the standard way to iterate over all characters in a StringBuilder in Java?

The obvious route is to just convert it to a String then use toCharArray(). The problem is, I'm dealing with thousands of unique strings, with which I do a lot of appending, and I think I'm getting memory and performance issues from having to intern them all.

EDIT: to clarify, I'm not manually interning Strings, but my understanding was that they were automatically interned, and that if I called toString for a StringBuilder that they would be interned. Perhaps I have misunderstood.

like image 310
jmite Avatar asked Jul 14 '14 17:07

jmite


People also ask

How do I iterate over StringBuilder?

Loop over chars.A for-loop can iterate over the characters in a StringBuilder. We access the length() method to get the StringBuilder's size and then use charAt() to access chars. Length This method returns the count of characters in the StringBuilder. The highest index is the count of chars minus one.

What is the correct way of comparing string and StringBuilder?

We can approach comparing String and StringBuilder by creating an instance of the String and StringBuilder classes. We will perform concatenation of String instances with the += operator and concatenation of StringBuilder instances with the . append() method.

Which method is used to iterate over each element?

An iterator method or get accessor performs a custom iteration over a collection. An iterator method uses the yield return statement to return each element one at a time.


1 Answers

First off, if you're interning lots of strings, you're doing something very wrong.

More generally, StringBuilder implements CharSequence, just like String. Use an ordinary counter-based for loop and charAt().

like image 94
chrylis -cautiouslyoptimistic- Avatar answered Oct 13 '22 05:10

chrylis -cautiouslyoptimistic-