1

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.

1

6 Answers 6

1

Using Java 9 codePoints stream you can reverse a string as follows. This example shows the reversal of a string containing surrogate pairs. It works with regular characters as well.

String str = "𝕙𝕖𝕝𝕝𝕠 𝕨𝕠𝕣𝕝𝕕";
String reversed = str.codePoints()
        // Stream<String>
        .mapToObj(Character::toString)
        // concatenate in reverse order
        .reduce((a, b) -> b + a)
        .get();

System.out.println(reversed); // 𝕕𝕝𝕣𝕠𝕨 𝕠𝕝𝕝𝕖𝕙

See also: Reverse string printing method

Sign up to request clarification or add additional context in comments.

Comments

0

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).

Comments

0

Use the built-in reverse() method of the StringBuilder class.

private static void palindrome() {
    String name1;
    StringBuilder input = new StringBuilder();
    System.out.println("Enter your name");
    Scanner tim = new Scanner(System.in);
    name1 = tim.next();
    input.append(name1);
    input.reverse();
    System.out.println(input);
}

Comments

0

Added reverse() function for your understanding

import java.util.Scanner;

public class P3 {
    public static void main(String[] args) {
        palindrome();
    }

    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();

        String nameReversed = reverse(name1);
        int len = name1.length();
        for (int i = 0; i < len; ++i) {
            char b = name1.charAt(i);
            System.out.println(b + " ");
        }
    }

    private static String reverse(String name1) {
        char[] arr = name1.toCharArray();
        int left = 0, right = arr.length - 1;
        while (left < right) {
            //swap characters first and last positions
            char temp = arr[left];
            arr[left++] = arr[right];
            arr[right--] = temp;
        }
        return new String(arr);
    }
}

1 Comment

Am gettin an error at line 109:stringindeoutofboundsexception
0

you can try the build-in function charAt()

private String reverseString2(String str) {
    if (str == null) {
        return null;
    }
    String result = "";
    for (int i = str.length() - 1; i >= 0; i--) {
        result = result + str.charAt(i);
    }
    return result;
}

public void test(){
    System.out.println(reverseString2("abcd"));
}

see also rever a string in java

Comments

0
String reversed = new StringBuilder(originalString).reverse().toString();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.