Sunday, 14 June 2020

Reversing a string in java 2023

 Reversing a string in java

class StringReverseDemo {
    public static void main(String[] args) {
        String str = "Hello";     
                     
        // convert string into char array and store in tempArray.
       
            char[] temp = str.toCharArray();

        char[] charRevArray = new char[str.length()];

        // copying the values of temp array to charRevArray in reverse order.

        for (int j = 0; j < str.length(); j++) {
            charRevArray[j] = temp [str.length() - 1 - j];
        }
       
        // convert char array to String.

        String reversePalindrome = new String(charRevArray);

        System.out.println("original strinr = "+str);
        System.out.println("Reverse = "+charRevArray);
    }
}

No comments:

Post a Comment