mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-05 16:27:33 +08:00
Add reverseUsingStringBuilder method to reverse a string (#6182)
This commit is contained in:
@ -36,4 +36,25 @@ public final class ReverseString {
|
||||
}
|
||||
return new String(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse version 3 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 reverse3(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();
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user