What is the most efficient way to reverse a string in Java? Should I use some sort of xor operator? The easy way would be to put all the chars in a stack and put them back into a string again but I doubt that's a very efficient way to do it.
And please do not tell me to use some built in function in Java. I am interested in learning how to do it not to use an efficient function but not knowing why it's efficient or how it's built up.
One variant can be, swapping the elements.
The fastest way would be to use the
reverse()
method on theStringBuilder
orStringBuffer
classes :)If you want to implement it yourself, you can get the character array, allocate a second character array and move the chars, in pseudo code this would be like:
You could also run half the array length and swap the chars, the checks involved slow things down probably.
Of course this is the most efficient way:
But if you don't like using that then I recommend this instead: