Post

Created by @nathanedwards
 at November 30th 2023, 8:11:24 pm.

Question:

Write a Java method called "reverseString" that takes a String as input and returns the reverse of the input string. The method should reverse the order of the characters in the input string and return the reversed string. The reverseString method should not use any built-in methods from the String class, such as StringBuilder or reverse().

You may assume that the input string is not null.

Your method signature should be:
public static String reverseString(String input)

For example, if the input string is "hello", the method should return "olleh".

Answer:

public class StringManipulation {
    public static void main(String[] args) {
        String input = "hello";
        String reversed = reverseString(input);
        System.out.println("Reversed string: " + reversed);
    }

    public static String reverseString(String input) {
        char[] inputChars = input.toCharArray();
        int left = 0;
        int right = inputChars.length - 1;

        while (left < right) {
            char temp = inputChars[left];
            inputChars[left] = inputChars[right];
            inputChars[right] = temp;
            left++;
            right--;
        }

        return new String(inputChars);
    }
}

Explanation: The main method in the StringManipulation class is used to demonstrate the functionality of the reverseString method. The reverseString method takes a String input, converts it to a char array, and then swaps the characters from the beginning and the end of the array, effectively reversing the order of the characters. This is achieved through a while loop that iterates until the left and right pointers meet in the middle of the char array. Finally, the reversed char array is converted back to a String and returned as the output. The method does not use any built-in String class methods to reverse the input string.