Reverse a string in Java

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

    Since the below method (using XOR) to reverse a string is not listed, I am attaching this method to reverse a string.

    The Algorithm is based on :

    1.(A XOR B) XOR B = A

    2.(A XOR B) XOR A = B

    Code snippet:

    public class ReverseUsingXOR {
        public static void main(String[] args) {
            String str = "prateek";
            reverseUsingXOR(str.toCharArray());
        }   
    
        /*Example:
         * str= prateek;
         * str[low]=p;
         * str[high]=k;
         * str[low]=p^k;
         * str[high]=(p^k)^k =p;
         * str[low]=(p^k)^p=k;
         * 
         * */
        public static void reverseUsingXOR(char[] str) {
            int low = 0;
            int high = str.length - 1;
    
            while (low < high) {
                str[low] = (char) (str[low] ^ str[high]);
                str[high] = (char) (str[low] ^ str[high]);   
                str[low] = (char) (str[low] ^ str[high]);
                low++;
                high--;
            }
    
            //display reversed string
            for (int i = 0; i < str.length; i++) {
                System.out.print(str[i]);
            }
        }
    
    }
    

    Output:

    keetarp

提交回复
热议问题