Java – print the inversion of any string without using any predefined functions?
•
Java
How to print the reverse of string Java is an object-oriented language without using any predefined functions, such as reverse()?
Solution
You can do this recursively or iteratively (loop)
Iteration:
static String reverseMe(String s) { StringBuilder sb = new StringBuilder(); for(int i = s.length() - 1; i >= 0; --i) sb.append(s.charAt(i)); return sb.toString(); }
Recursion:
static String reverseMe(String s) { if(s.length() == 0) return ""; return s.charAt(s.length() - 1) + reverseMe(s.substring(0,s.length()-1)); }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码