public class ReverseWordsInString {
public String reverse(String input) {
if (input.isEmpty()) { (1)
return input;
}
String[] arr = input.split(" ", 2); (2)
String firstWord = arr[0];
String remainingSentence;
if (arr.length == 2)
remainingSentence = arr[1];
else
remainingSentence = "";
return reverse(remainingSentence) + firstWord + " "; (3)
}
}
Reverse position of words in a string using recursion
Upasana | November 20, 2020 | | 83 views | Java Coding Challenges
In this article, we will write a program to reverse position of words in a given string using recursive approach.
Sample input
I am the best of bests
Output
bests of best the am I
Recursive Approach
-
We will remove first word from the input string and append it at the end.
-
Repeat it till all the words are removed and input becomes empty.
Java source
Reverse position of words in a string using Recusion Java
1 | Base condition in recursion, if the input is empty then we just return (unwind the stack in recursion) |
2 | We are splitting input string into two parts - first element of array will contain the first word, second element of array will contain the remaining sentence |
3 | Tail recursion - removes first word and appends it to the last |
JUnit testcase
We will write a simple Junit based testcase to assert the correctness of our given program.
JUnit Test
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.*;
public class ReverseWordsInStringTest {
@Test
public void reverse() {
ReverseWordsInString utils = new ReverseWordsInString();
assertThat(utils.reverse("I am the best of bests"), equalTo("bests of best the am I"));
}
}
That’s all.
Java Coding Challenges:
- Check if the given string is palindrome
- Find two numbers of which the product is maximum in an array
- Prime number checker in Java
- Create anagram buckets from a given input array of words
- Anagrams string checker in Java
- Reverse a string using recursion in Java
- Java Program to find Factorial of a number
Top articles in this category:
- Reverse a string using recursion in Java
- Reverse order of words inside string in Java
- Java Coding Problems for SDET Automation Engineer
- Create anagram buckets from a given input array of words
- Get distinct words from a given file in Java
- Java Program to find Factorial of a number
- 50 Java Interview Questions for SDET Automation Engineer
Recommended books for interview preparation:
Book you may be interested in..
Book you may be interested in..