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.
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.
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.
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.
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()
.
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