Reverse a string in Java

前端 未结 30 2633
礼貌的吻别
礼貌的吻别 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 14:04

    I tried, just for fun, by using a Stack. Here my code:

    public String reverseString(String s) {
        Stack stack = new Stack<>();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            stack.push(s.charAt(i));
        }
        while (!stack.empty()) {
            sb.append(stack.pop());
        }
        return sb.toString();
    
    }
    

提交回复
热议问题