Skip to content

Commit 9ffc962

Browse files
author
“gozhort”
committed
feat: add reverseUsingStringBuilder method to reverse a string
1 parent 63ce6b8 commit 9ffc962

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

src/main/java/com/thealgorithms/strings/ReverseStringRecursive.java

+21
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,25 @@ public static String reverse(String str) {
1818
return reverse(str.substring(1)) + str.charAt(0);
1919
}
2020
}
21+
22+
/**
23+
* Reverses the given string using a StringBuilder.
24+
* This method converts the string to a character array,
25+
* iterates through it in reverse order, and appends each character
26+
* to a StringBuilder.
27+
*
28+
* @param string The input string to be reversed.
29+
* @return The reversed string.
30+
*/
31+
public static String reverseUsingStringBuilder(String string){
32+
if (string.isEmpty()){
33+
return string;
34+
}
35+
char[] chars = string.toCharArray();
36+
StringBuilder sb = new StringBuilder();
37+
for (int i = string.length() -1; i >= 0; i--){
38+
sb.append(chars[i]);
39+
}
40+
return sb.toString();
41+
}
2142
}

src/test/java/com/thealgorithms/strings/ReverseStringRecursiveTest.java

+7
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,11 @@ public class ReverseStringRecursiveTest {
1313
testReverseString(String input, String expectedOutput) {
1414
assertEquals(expectedOutput, ReverseStringRecursive.reverse(input));
1515
}
16+
17+
@ParameterizedTest
18+
@CsvSource({"'Hello World', 'dlroW olleH'", "'helloworld', 'dlrowolleh'", "'123456789', '987654321'", "'', ''", "'A', 'A'", "'!123 ABC xyz!', '!zyx CBA 321!'", "'Abc 123 Xyz', 'zyX 321 cbA'", "'12.34,56;78:90', '09:87;65,43.21'", "'abcdEFGHiJKL', 'LKJiHGFEdcba'",
19+
"'MixOf123AndText!', '!txeTdnA321fOxiM'"})
20+
public void testReverseWithLoop(String input, String expectedOutput) {
21+
assertEquals(expectedOutput, ReverseStringRecursive.reverseUsingStringBuilder(input));
22+
}
1623
}

0 commit comments

Comments
 (0)