When I do algorithm exercises, I found many people like to transfer a string to charArray before do operations?
I don't understand why do we bother do that? I mean, I can use string.charAt(), why use string.toCharArray() and then charArray[i]? It's the same and even charArray use O(n) memory.
Can anyone explain that to me?
Stringis immutable thus, if you want to manipulate the string it's always faster to generate the charArray first. And the access of an array-element is way faster thancharAt. Would expand this to an answer, but since @SotiriosDelimanolis closed the question for no reason...StringBufferis a mutable string, and still hasindexOf()and all the usualStringstuff. docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html. SoStringbeing immutable isn't sufficient explanation. StringBuffer was in JDK1.0, so it's not new. There must be some other reason it doesn't get used. I'd guess probably working with an array ofcharis more straightforward.StringBufferandStringare two completely different things.Stringis immutable,StringBufferisn't since it's purpose is to manipulate Strings. But in general it's way faster to manipulate an array than callingcharAt. Might be more straightforward aswell, but it's rather a matter of personal coding-style than anything else.