Reverse words in a given String using recursion
Reverse words in a given String using recursion. We need to reverse words by words in a given line and not the character in a given string. We need to solve this by using backtracking and recursion logic.
Let's see simple Java code for getting the given of words in a reverse order by using recursion.
OUTPUT:
Let's see simple Java code for getting the given of words in a reverse order by using recursion.
public class ReverseLineByWords { public static void main(String[] args) { String str = "Hello Java Discover"; String finalStr = new ReverseLineByWords().reverseLine(str); System.out.println(finalStr); } public String reverseLine(String str){ String word = ""; int i = 0; for(;i<str.length();i++){ if(str.charAt(i) == ' ') { word = word + " "; break; }else{ word = word + str.charAt(i); } } if(i < str.length()) return reverseLine(str.substring(i+1)) + word; return (word + " "); } }
OUTPUT:
Discover Java Hello