Skip to content

Commit 849ab91

Browse files
Add reverseUsingStringBuilder method to reverse a string (#6182)
1 parent df6da47 commit 849ab91

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

Diff for: src/main/java/com/thealgorithms/strings/ReverseString.java

+21
Original file line numberDiff line numberDiff line change
@@ -36,4 +36,25 @@ public static String reverse2(String str) {
3636
}
3737
return new String(value);
3838
}
39+
40+
/**
41+
* Reverse version 3 the given string using a StringBuilder.
42+
* This method converts the string to a character array,
43+
* iterates through it in reverse order, and appends each character
44+
* to a StringBuilder.
45+
*
46+
* @param string The input string to be reversed.
47+
* @return The reversed string.
48+
*/
49+
public static String reverse3(String string) {
50+
if (string.isEmpty()) {
51+
return string;
52+
}
53+
char[] chars = string.toCharArray();
54+
StringBuilder sb = new StringBuilder();
55+
for (int i = string.length() - 1; i >= 0; i--) {
56+
sb.append(chars[i]);
57+
}
58+
return sb.toString();
59+
}
3960
}

Diff for: src/test/java/com/thealgorithms/strings/ReverseStringTest.java

+6
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,10 @@ public void testReverseString(String input, String expectedOutput) {
2525
public void testReverseString2(String input, String expectedOutput) {
2626
assertEquals(expectedOutput, ReverseString.reverse2(input));
2727
}
28+
29+
@ParameterizedTest
30+
@MethodSource("testCases")
31+
public void testReverseString3(String input, String expectedOutput) {
32+
assertEquals(expectedOutput, ReverseString.reverse3(input));
33+
}
2834
}

0 commit comments

Comments
 (0)