Reverse a string in Java

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

    For Online Judges problems that does not allow StringBuilder or StringBuffer, you can do it in place using char[] as following:

    public static String reverse(String input){
        char[] in = input.toCharArray();
        int begin=0;
        int end=in.length-1;
        char temp;
        while(end>begin){
            temp = in[begin];
            in[begin]=in[end];
            in[end] = temp;
            end--;
            begin++;
        }
        return new String(in);
    }
    

提交回复
热议问题