Search code examples
javastringcharacterreverse

Reverse String characters in java


Am trying to reverse a string using a method in java, I can fetch all the elements of the string and print them out in order via a loop, my problem is reversing the string such that the first comes last and the last comes first, I tried to find a reverse function to no avail... Here is what I have so far...

private static void palindrome() {
    char[] name = new char[]{};
    String name1;
    System.out.println("Enter your name");
    Scanner tim = new Scanner(System.in);
    name1 = tim.next();
    int len = name1.length();
    for (int i = 0; i <= len; ++i) {
        char b = name1.charAt(i);
        System.out.println(b + " ");
    }
}

That loop succeeds in printing out the single characters from the string.


Solution

  • You simply need to loop through the array backwards:

    for (int i = len - 1; i >= 0; i--) {
        char b = name1.charAt(i);
        System.out.println(b + " ");
    }
    

    You start at the last element which has its index at the position length - 1 and iterate down to the first element (with index zero).

    This concept is not specific to Java and also applies to other data structures that provide index based access (such as lists).