Reverse a string in Java

前端 未结 30 2600
礼貌的吻别
礼貌的吻别 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:59

    1. Using Character Array:

    public String reverseString(String inputString) {
        char[] inputStringArray = inputString.toCharArray();
        String reverseString = "";
        for (int i = inputStringArray.length - 1; i >= 0; i--) {
            reverseString += inputStringArray[i];
        }
        return reverseString;
    }
    

    2. Using StringBuilder:

    public String reverseString(String inputString) {
        StringBuilder stringBuilder = new StringBuilder(inputString);
        stringBuilder = stringBuilder.reverse();
        return stringBuilder.toString();
    }
    

    OR

    return new StringBuilder(inputString).reverse().toString();
    

提交回复
热议问题