C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
And: We use the String constructor to create a string from the char buffer we filled in the loop.
ConstructorsAnd: We assign the array elements to a string character indexed from the opposite (inverted) side. This reverses the characters.
Char ArraysFinally: We create a string and return it. In main we find that the reverseString works as expected on simple strings.
Java program that reverses Strings
public class Program {
public static String reverseString(String value) {
// Create a char buffer.
char[] array = new char[value.length()];
for (int i = 0; i < array.length; i++) {
// Assign to the array from the string in reverse order.
// ... charAt uses an index from the last.
array[i] = value.charAt(value.length() - i - 1);
}
return new String(array);
}
public static void main(String[] args) {
// Test our reverse string method.
String original = "abc";
String reversed = reverseString(original);
System.out.println(original);
System.out.println(reversed);
original = "qwerty";
reversed = reverseString(original);
System.out.println(original);
System.out.println(reversed);
}
}
Output
abc
cba
qwerty
ytrewq
But: Collections.reverse would require the string be converted into a collection like an ArrayList. This would hinder performance.
ArrayList