Reverse a String Without Using Built-In Functions

Problem Statement:

Create a Java program to reverse a string without using built-in functions.

Input:

A string consisting of alphanumeric characters and spaces.

Example:

Input: "hello world"
Output: "dlrow olleh"

Step-by-Step Solution:

Step 1: Convert the string to a character array

  • Convert the input string into a character array to manipulate individual characters.
char[] charArray = str.toCharArray();

Step 2: Initialize two pointers

  • Use two pointers: one at the beginning of the array and one at the end.
int start = 0;
int end = charArray.length - 1;

Step 3: Swap characters

  • Swap characters at the start and end pointers, then move the pointers towards the center until they meet.
while (start < end) {
    // Swap characters
    char temp = charArray[start];
    charArray[start] = charArray[end];
    charArray[end] = temp;

    // Move pointers
    start++;
    end--;
}

Step 4: Convert the character array back to a string

  • After swapping, convert the character array back to a string.
String reversedString = new String(charArray);

Complete Solution:

public class ReverseString {
    public static void main(String[] args) {
        String str = "hello world";
        System.out.println("Original String: " + str);
        String reversed = reverseString(str);
        System.out.println("Reversed String: " + reversed);
    }

    public static String reverseString(String str) {
        // Step 1: Convert to character array
        char[] charArray = str.toCharArray();

        // Step 2: Initialize pointers
        int start = 0;
        int end = charArray.length - 1;

        // Step 3: Swap characters
        while (start < end) {
            char temp = charArray[start];
            charArray[start] = charArray[end];
            charArray[end] = temp;

            start++;
            end--;
        }

        // Step 4: Convert back to string
        return new String(charArray);
    }
}

Explanation:

  • Convert to Array: Converting the string to a character array allows for easy manipulation of characters.
  • Pointer Swapping: Using two pointers to swap characters in place ensures that we reverse the string efficiently.
  • Convert Back: After reversing, converting the character array back to a string gives us the final result.

Example:

String original = "Java programming";
String reversed = reverseString(original);
System.out.println(reversed); // Output: "gnimmargorp avaJ"