Reverse String Alternatives in Java [Snippets]
Sometimes, you've got to think outside of the box.
Join the DZone community and get the full member experience.
Join For FreeRecently, I came across a request to reverse a given string in Java. This does seem a bit odd, but nonetheless, I was asked to perform a reverse without using in-built methods, additional parameters, or any other common way. I am not sure if other companies follow this trend of not using Java API methods, but still, in interviews, companies want you to think beyond what you know and would typically do.
You may also like: The Right Way to Reverse a String in Java
Reversing a string becomes much easier with Java reverse()
in the AbstractStringBuilder
class method, which takes care of all wired scenarios.
Let's try out some different ways to reverse a Java string
1. Reverse String Without Using Temp Variable (Recursive)
private String reverseString(String original) {
if(original.isEmpty()) {
return original;
}
return reverseString(original.substring(1)) + original.charAt(0);
}
Other than the above, below are few more ways to perform a reverse string:
2. Using the Reverse Method
private String reverseString(String original){
return new StringBuilder(original).reverse().toString();
}
3. Using RLO Character
private String reverseString(String original){
return "\u202E" + original;
}
4. Using the SubString Method
private String reverseString(String str){
// base case: if string is null or empty
if (str == null || str.equals(""))
return str;
// last character + recur for remaining string
return str.charAt(str.length() - 1) +
reverse(str.substring(0, str.length() - 1));
}
We hope you enjoyed these alternative ways of reversing a string in Java. Happy coding!
Further Reading
Opinions expressed by DZone contributors are their own.
Trending
-
Effective Java Collection Framework: Best Practices and Tips
-
Integration Testing Tutorial: A Comprehensive Guide With Examples And Best Practices
-
How To Scan and Validate Image Uploads in Java
-
How Agile Works at Tesla [Video]
Comments