How to Reverse String in Java.
Reverse String in Java. String can be reversed using Iterative and Recursive approach. We will Reverse a String using Recursion and using loop. For reversing a String we should not use any inbuilt methods.
Input: "Reverse String"
Output: "gnirtS esreveR"
Input: "HELLO"
Output: "OLLEH"
Input: "123 abc"
Output: "cba 321"
Algorithm
1. Reverse a String using Loop
STEP 1: Initialize i = string.length()-1 as we need to read the characters of String from back.
STEP 2: Iterate till i>=0, that is to read all the characters of array till first character present at index 0.
STEP 3: Decrement i-- at each iteration as we are printing backwards.
STEP 4: Using string.charAt(i), method, pick each character of String and Print it.
package javabypatel; public class ReverseStringInJava { public static void main(String[] args) { reverseString("Reverse String"); } public static void reverseString(String str){ for (int i = str.length()-1; i >= 0; i--) { System.out.print(str.charAt(i)); } } }
2. Reverse a String using Recursion
In this approach, we will Reverse a String using recursion.
In each Recursive step, we will pick character at index 0 and pass the remaining Substring to next Recursive call.
Repeat until substring length is not equal to 0. When substring length is == 0, Return String.
package javabypatel; public class ReverseStringInJava { public static void main(String[] args) { System.out.println(reverseString("JavaByPatel")); } public static String reverseString(String str) { if (str.length() == 0) return str; return reverseWord(str.substring(1)) + str.charAt(0); } }
You may also like to see
Compress a given string in-place and with constant extra space.
Check whether a given string is an interleaving of String 1 and String 2.
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord.
Serialize and Deserialize a Binary Tree
Advanced Multithreading Interview Questions In Java
Enjoy !!!!
If you find any issue in post or face any error while implementing, Please comment.
No comments:
Post a Comment