Skip to content

feat: add reverseUsingStringBuilder method to reverse a string #6182

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Feb 27, 2025
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,25 @@ public static String reverse(String str) {
return reverse(str.substring(1)) + str.charAt(0);
}
}

/**
* Reverses the given string using a StringBuilder.
* This method converts the string to a character array,
* iterates through it in reverse order, and appends each character
* to a StringBuilder.
*
* @param string The input string to be reversed.
* @return The reversed string.
*/
public static String reverseUsingStringBuilder(String string) {
if (string.isEmpty()) {
return string;
}
char[] chars = string.toCharArray();
StringBuilder sb = new StringBuilder();
for (int i = string.length() - 1; i >= 0; i--) {
sb.append(chars[i]);
}
return sb.toString();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,12 @@ public class ReverseStringRecursiveTest {
testReverseString(String input, String expectedOutput) {
assertEquals(expectedOutput, ReverseStringRecursive.reverse(input));
}

@ParameterizedTest
@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'",
"'MixOf123AndText!', '!txeTdnA321fOxiM'"})
public void
testReverseUsingStringBuilder(String input, String expectedOutput) {
assertEquals(expectedOutput, ReverseStringRecursive.reverseUsingStringBuilder(input));
}
}