Reverse a string in Java

前端 未结 30 2595
礼貌的吻别
礼貌的吻别 2020-11-21 13:12

I have \"Hello World\" kept in a String variable named hi.

I need to print it, but reversed.

How can I do this? I understand there

30条回答
  •  余生分开走
    2020-11-21 13:46

    Here is an example using recursion:

    public void reverseString() {
        String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String reverseAlphabet = reverse(alphabet, alphabet.length()-1);
    }
    
    String reverse(String stringToReverse, int index){
        if(index == 0){
            return stringToReverse.charAt(0) + "";
        }
    
        char letter = stringToReverse.charAt(index);
        return letter + reverse(stringToReverse, index-1);
    }
    

提交回复
热议问题