settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Reverse String - Java Task (StringBuilder)

+13 votes

Write a program that reads a string from the console, reverses it and prints the result back at the console.

Examples:

Input

Output

sample

elpmas

24tvcoi92

29iocvt42

 

asked in Java category by user ak47seo

2 Answers

+2 votes

Here's my solution:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Pr_01_ReverseString {
    public static void main(String[] args) throws IOException {

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        String input = reader.readLine();
        StringBuilder sb = new StringBuilder();

        for (int i = input.length() - 1; i >= 0; i--) {//REVERSE ORDER
            sb.append(input.charAt(i));
        }
        System.out.println(sb.toString());
    }
}
answered by user andrew
+1 vote

Here's another without fori (for iteration):
 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Pr_01_ReverseString {
    public static void main(String[] args) throws IOException {

        try (BufferedReader bf = new BufferedReader(new InputStreamReader(System.in))) {
            String a = bf.readLine();
            StringBuilder b = new StringBuilder(a);
            b.reverse();
            System.out.println(b);
        }
    }
}

 

answered by user eiorgert
...