You can easily reverse a string using the java.lang.StringBuilder.reverse() method. But in programming interviews, you will be asked to write a program that can do the same thing without using the native function.
To increase the complexity, they can even ask you to not use any other StringBuilder, StringBuffer, or a String object. The below code is an attempt to do just that.
The process
- Creates a new StringBuilder object with our text.
- Calculate the length of the text. This will be used in our for-loop.
- Now run the loop from starting of the text to the end. On every iteration, we are taking the last character of the string which we have not processed, and then we are appending it to the end of our string. As we are starting from the last element, we will get the characters in the reverse order.
- As we have appended the reverse string, it will be added after the initial characters. So we are safely deleting the previous characters that were given to us as the input.
Key Concepts
- str.substring(2, 4): Returns the characters from index 2 to index 4 from the StringBuilder object. Like “to” from “Mstoic”
- str.append(” Team”): Appends the given string to the end of the previous string. If str contains “Editorial”, after appending, it becomes “Editorial Team”.
- str.delete(0,10): Deletes characters from the StringBuilder object, starting from the index specified in parameter one to the index specified in parameter two. If the string is “Editorial Team”, and we execute str2.delete(0, 7), our object will now contain “Team”.
Do let me know if there’s any better way to do this. I will happily add that to the article.