Joey Eremondi
Joey Eremondi

Reputation: 8423

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.

Upvotes: 10

Views: 37956

Answers (1)

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

Upvotes: 17

Related Questions