Home page

Saturday, June 10, 2023

Reverse String in JAVA

 public class StringReversalExample {

    public static void main(String[] args) {

        String str = "Hello, World!";

        String reversedString = reverseString(str);

        System.out.println("Reversed string: " + reversedString);

    }


    public static String reverseString(String str) {

        char[] charArray = str.toCharArray();

        int start = 0;

        int end = charArray.length - 1;


        while (start < end) {

            char temp = charArray[start];

            charArray[start] = charArray[end];

            charArray[end] = temp;

            start++;

            end--;

        }


        return new String(charArray);

    }

}

In this example, we have a method called reverseString() that takes a string as input and returns the reversed string.

Inside the reverseString() method, we convert the input string into a character array using toCharArray(). We initialize two pointers, start and end, where start points to the first character of the array and end points to the last character.

We then use a while loop to swap characters from both ends of the array until start becomes greater than end. In each iteration, we swap the characters at positions start and end, and then increment start and decrement end to move closer towards the center of the array.

Finally, we create a new string from the reversed character array using the String constructor, and return it as the result.

Output:
Reversed string: !dlroW ,olleH

No comments:

Post a Comment