How to Reverse a String in Java - The Coding Shala
Home >> Java Programs >> Reverse a String
Other Posts You May Like
In this post, we will learn how to Reverse a String in Java.
Reverse a String in Java
Given a string S as input. You have to reverse the given string.
Example:
Input:
3
Geeks
GeeksforGeeks
GeeksQuiz
Output:
skeeG
skeeGrofskeeG
ziuQskeeG
Approach 1
Using StringBuilder.
Java Program:
import java.util.*; import java.lang.*; import java.io.*; class GFG { public static void main (String[] args) { //code Scanner sc = new Scanner(System.in); int tc = sc.nextInt(); while(tc-- > 0) { String str = sc.next(); StringBuilder sb = new StringBuilder(str); sb.reverse(); System.out.println(sb.toString()); } } }
Approach 2
By using for loop from end to start.
Java Program:
import java.lang.*; import java.io.*; class GFG { public static void main (String[] args) { //code Scanner sc = new Scanner(System.in); int tc = sc.nextInt(); while (tc-- > 0) { String str = sc.next(); for(int i=str.length()-1; i>=0; i--){ System.out.print(str.charAt(i)); } System.out.println(); } } }
- Add Two Numbers in Java
- Sum of Digits of a Number
- Java Program to check leap year
- Add One to Number
- Repeat and Missing Number
Comments
Post a Comment