Java Program That Reads a Sentence and Outputs the Sentence in Reverse
Know How to Contrary A String In Java – A Beginners Guide
Last updated on Sep 30,2021 73.7K Views
String is a sequence of characters that is considered to be an object in Java. In Java, there are various operations that you tin can perform on the String object. One of the nigh widely used operations on a string object is String Reverse. In this commodity, I will tell you the various approaches to Reverse a String in Coffee.
In Java, a String can be reversed in five different ways. They are every bit follows:
- Opposite a String using CharAt Method
- String reverse using String Buffer/String Builder Approach
- Reverse a String using Reverse Iterative Approach
- String reverse using Recursion
- Reverse the letters present in the String
Now let'southward get into the details of each of these approaches starting off by understanding how to opposite a String in Coffee using CharAt method.
1. Reverse a String using CharAt Method
In the below given Coffee program volition aid yous to empathize how to reverse a String entered past the user. Hither, I accept used the CharAt() method in lodge to extract the characters from the input String. The chief task of the CharAt() method is to return the character at the specified index in the given String. So, I have appended them in reverse order to reverse the given String. It is one of the simple approaches to reverse a Cord in Java.
package Edureka; import coffee.util.*; public class StringReverse{ public static void principal(Cord args[]) { String initial, rev=""; Scanner in=new Scanner(Organization.in); Organization.out.println("Enter the string to reverse"); initial=in.nextLine(); int length=initial.length(); for(int i=length-one;i>=0;i--) rev=rev+initial.charAt(i); System.out.println("Reversed cord: "+rev); } } When you execute this program, the output looks similar as shown beneath:
Enter the string to reverse How-do-you-do EDUREKA Reversed string: AKERUDE OLLEH
I hope you understood how to opposite a given Java String with this simple approach. Now let's move further and understand how to opposite a String using Cord Buffer/ StringBuilder Class.
2. Reverse a Cord using String Builder / Cord Buffer Class
StringBuffer and StringBuilder contain of an inbuilt method reverse() which is used to reverse the characters in the StringBuffer. This method replaces the character sequence in the opposite order. Beneath is the code to reverse a String using a built-in method of the StringBuffer grade.
package Edureka; import java.util.*; public form StringRev{ // Function to reverse a string in Java using StringBuilder public static String rev(String south){ render new StringBuilder(s).reverse().toString(); } public static void main(String[] args){ String s= "Welcome to Edureka"; // Annotation that string is immutable in Java s= rev(s); System.out.println("Event after reversing a string is : "+s); } } On executing the above lawmaking, the output volition be as shown below:
Outcome after reversing a string is : akerudE ot emocleW
This is all nigh StringBuilder Class. Alternatively, you can also apply a StringBuffer class opposite() method only likeStringBuilder. Let'south take a look at the code beneath.
packet Edureka; import coffee.util.*; public class StringRev{ // Office to reverse a string in Java using StringBuffer public static String rev(String s){ return new StringBufferr(due south).reverse().toString(); } public static void main(String[] args){ String due south= "Welcome to Edureka"; // Note that string is immutable in Coffee due south= rev(due south); System.out.println("Result after reversing a string is : "+s); } } When you run the program, the output will the same equally that of the StringBuilder class.
Note: You can either contrary as String using StringBuffer reverse() as shown in the above program or you lot can simply use the lawmaking logic as shown beneath:
StringBuffer sb =new StringBuffer("JavaEdureka"); System.out.println(sb.reverse()); Output: akerudEavaJ Both StringBuilder and StringBuffer has the same approach of reversing a String in Java. But, StringBuilder is preferred as information technology is not synchronized and is faster than StringBuffer. Having understood this, let's delve deeper into this commodity and learn one more than approach to reverse a Cord in Java.
3. Reversing a String using Reverse Iteration
In this approach, I accept outset converted the given String to Grapheme Array using CharArray() method. After that, I have simply iterated the given array in the contrary lodge.
package Edureka; import coffee.util.*; public grade StringRev{ // Function to reverse a cord in Java public static Cord reverseString(String due south){ //Converting the cord into a character array char c[]=s.toCharArray(); String reverse=""; //For loop to reverse a string for(int i=c.length-i;i>=0;i--){ reverse+=c[i]; } return reverse; } public static void main(Cord[] args) { Organization.out.println(reverseString("Hi All")); Organization.out.println(reverseString("Welcome to Edureka Blog")); } } Output:
llA iH golB akerudE ot emocleW
I promise yous understood how to use reverse iteration approach to reverse a String in Java. Now let's move further and understand reversing a String using recursion.
iv. String Reverse using Recursion
Recursion is nothing just a function that calls itself. In this approach, I volition write a method which reverses the Cord by calling itself recursively. Let's implement and check how it works.
package Edureka; import java.util.*; public course StringRecursion{ String rev(Cord str) { if(str.length() == 0) render " "; render str.charAt(str.length()-1) + rev(str.substring(0,str.length()-1)); } public static void main(String[ ] args) { StringRecursion r=new StringRecursion(); Scanner sc=new Scanner(System.in); System.out.print("Enter the string : "); String s=sc.nextLine(); Organisation.out.println("Reversed String: "+r.rev(s)); } } Output:
Enter the string : Java is the blooming engineering since its existence Reversed String: ecnetsixe sti ecnis ygolonhcet gnimoolb eht si avaJ
In the higher up code, I created the object for the class StringRecursion r. And so, I have read the entered Cord using sc.nextLine() and stored it in the String variable south . Finally, I chosen the opposite method as r.rev(south) . Having understood this, let's now understand the terminal approach in this article. Here, I will tell y'all how to contrary the messages present in the given String.
5. Reverse the letters present in the String
This Coffee program reverses letters nowadays in a S tring entered past the user. It doesn't reverse the entire String every bit seen earlier in the previous approaches. For Instance: Hello People volition be termed as olleH elpoeP. Let'southward implement the aforementioned using Java.
package Edureka; public form stringreverse { public static void master(String[] args) { // TODO Auto-generated method stub String str = "Welcome To Edureka"; String[] strArray = str.separate(" "); for (Cord temp: strArray){ System.out.println(temp); } for(int i=0; i<3; i++){ char[] s1 = strArray[i].toCharArray(); for (int j = s1.length-1; j>=0; j--) {System.out.print(s1[j]);} System.out.impress(" "); } } } The output of the in a higher place program will be as shown beneath:
Welcome To Edureka emocleW oT akerudE
Then, that was all most reversing the messages in the given String. This brings us to the finish of the article on Opposite a String in Coffee. I hope you establish it informative.
Check out theCoffee Training past Edureka, a trusted online learning visitor with a network of more 250,000 satisfied learners spread across the globe. We are here to help you with every step on your journeying, for becoming a likewise this java interview questions, we come with a curriculum which is designed for students and professionals who want to be a Java Developer.
Got a question for united states? Delight mention it in the comments section of this "Reverse a String in Java " article and nosotros will get dorsum to you as soon as possible or join our Java Training in Padang.
Source: https://www.edureka.co/blog/reverse-a-string-in-java/
0 Response to "Java Program That Reads a Sentence and Outputs the Sentence in Reverse"
Post a Comment