Easy way to reverse String

后端 未结 12 1022
野性不改
野性不改 2021-02-13 04:01

Without going through the char sequence is there any way to reverse String in Java

12条回答
  •  攒了一身酷
    2021-02-13 04:36

    You can use String buffer to reverse a string.

    public String reverse(String s) {
        return new StringBuffer(s).reverse().toString();
    }
    

    one more interesting way to do this is recursion.

    public String reverse(String s) {
        if (s.length() <= 1) { 
            return s;
        }
        return reverse(s.substring(1, s.length())) + s.charAt(0);
    }
    

提交回复
热议问题