Skip to content

Commit 3358099

Browse files
reverse String in Java using Iteration & Recusrion
reverse String in Java using Iteration and Recursion? (solution) Your task is to write a program to reverse String in Java without using StringBuffer class. You also need to provide both iterative and recursive algorithm for String reversal. You can use other String utility methods e.g. charAt(), toCharArray() or substring() from java.lang.String class.
1 parent 639b4b6 commit 3358099

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

Challenge04.java

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package challenge04;
2+
3+
import static org.junit.Assert.assertTrue;
4+
5+
import org.junit.jupiter.api.Test;
6+
7+
/**
8+
* The Class Challenge04.
9+
*
10+
* Reverse String in Java using Iteration and Recursion?
11+
*/
12+
public class Challenge04 {
13+
14+
public static String reverseUsingIteration(String input) {
15+
int len = input.length();
16+
char[] c = new char[len];
17+
len--;
18+
for (int i = 0; i <= len; i++) {
19+
c[i] = input.charAt(len - i);
20+
}
21+
return new String(c);
22+
23+
}
24+
25+
public static String reverse(String input){
26+
27+
if(input.length()<2){
28+
return input;
29+
}
30+
31+
return reverse(input.substring(1)) + input.charAt(0);
32+
}
33+
@Test
34+
public void test() {
35+
assertTrue(Challenge04.reverse("Hello").equals("olleH"));
36+
assertTrue(Challenge04.reverseUsingIteration("Hi Hello How are you").equals("uoy era woH olleH iH"));
37+
38+
}
39+
}

0 commit comments

Comments
 (0)