[Solved] Reverse String - Java Task (StringBuilder)

  

8
Topic starter

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

Examples:

reverse string
2 Answers
7

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

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);
        }
    }
}
Share: