The previous solution given will work! I'm going to suggest some modifications. Here's the original:
public static String reverse(String str) {
String reversed = "";
for (int i = str.length() - 1; i >= 0; i--) {
reversed += str.substring(i, i + 1);
}
return reversed;
}
That call to str.substring(i, i + 1) is essentially a way of picking out a single character at index i, but there's actually a built in String method for that: charAt. And I think things read a bit more easily using it. Using it is also a bit semantically clearer in my opinion (others can disagree!):
public static String reverse(String str) {
String reversed = "";
for (int i = str.length() - 1; i >= 0; i--) {
reversed += str.charAt(i);
}
return reversed;
}
It's generally better to use a StringBuilder, though, since that keeps us from generating a lot of Strings along the way (what if our input String was a very long String)?
public static String reverse(String str) {
StringBuilder reversed = new StringBuilder();
for (int i = 0; i < str.length(); ++i) {
reversed.insert(0, str.charAt(i));
}
return reversed.toString();
}
Note that here, I actually iterated forward through the String and prepended (using insert), but you could iterate backwards and use the append method, too. But the main point is that using a StringBuilder keeps us from having to generate new Strings for each character in the input.
I hope that helps!