Post

Created by @nathanedwards
 at October 31st 2023, 2:53:03 pm.

AP Computer Science Exam Question

Instructions:

Write a Java method reverseString that takes a String as input and returns the reversed version of the input string.

The reversed string should be created by reversing the order of characters in the original string.

For example:

  • If the input string is "hello", the method should return "olleh".
  • If the input string is "abcdefg", the method should return "gfedcba".

You must use String manipulation techniques to solve this problem. Do not use any built-in string reversal functions.

Your Answer:

public class ReverseStringExample {
    
    public static String reverseString(String str) {
        int len = str.length();
        StringBuilder reversedStr = new StringBuilder();

        for (int i = len - 1; i >= 0; i--) {
            reversedStr.append(str.charAt(i));
        }

        return reversedStr.toString();
    }
    
    public static void main(String[] args) {
        String input1 = "hello";
        String input2 = "abcdefg";

        String reversed1 = reverseString(input1);
        String reversed2 = reverseString(input2);

        System.out.println("Reversed string of \"" + input1 + "\": " + reversed1);
        System.out.println("Reversed string of \"" + input2 + "\": " + reversed2);
    }
}

Explanation:

The given problem asks us to reverse a given string without using any built-in string reversal functions.

In the solution provided above, we start by initializing the reversedStr variable as a StringBuilder object that will store the reversed string.

We then iterate through each character of the input string str in reverse order. This is achieved by starting the loop at len - 1 index and decrementing i until it reaches 0.

Inside the loop, we use the charAt method to retrieve the character at index i and append it to the reversedStr using the append method of StringBuilder.

Finally, we convert the StringBuilder object back to a string using the toString method and return the reversed string.

In the main method, we demonstrate the usage of the reverseString method by providing two test cases. We print the reversed string of each test case to verify the correctness of our reverseString implementation.