tags:

views:

260

answers:

3

I need to reverse the string of a user's input.

I need it done in the simplest of ways. I was trying to do reverseOrder(UserInput) but it wasn't working.

For example, user inputs abc I just take the string and print out cba

+7  A: 
new StringBuilder(str).reverse().toString()

java.util.Collections.reverseOrder is for sorting in reverse of normal order.

Tom Hawtin - tackline
Is it common practice here for the biggest point-earners to answer people's homework problems?
Jonathan Feinberg
It's not immediately obvious that that is the easy way to reverse a string.
Tom Hawtin - tackline
Wtf? This isn't homework... I'm assuming since it's so basic you assumed it was?
Phil
@Jonathan Feinberg: No.
Greg Hewgill
(As it happens, I think I found out the `StringBuffer.reverse` (no `StringBuilder` in those days) trick from Jon Skeet.)
Tom Hawtin - tackline
@Jonathan: Nope. Homework would have go in the lines of `char [] chars = "ab".toCharArray(); for etc etc etc` Teachers *regularly* don't accept library calls solutions.
OscarRyz
@Oscar @Phil.. Look at the Tags, this is homework. And there is no teacher here condoning a library call either.
No longer a user
@Nate: Phil is the topic starter. I feel we should give him the benefit of the doubt before condemning him.
Hooked
+2  A: 

I prefer using Apache's commons-lang for this kind of thing. There are all kinds of goodies, including:

StringUtils.reverse("Hello World!");

yields: !dlroW olleH

StringUtils.reverseDelimited("Hello World!", ' ');

yields: World! Hello

SingleShot
+1  A: 

If you are new to programming, which I guess you are, my suggestion is "Why use simple stuff?". Understand the internals and play some!!

public static void main(String[] args) {
String str = "abcasz";
char[] orgArr = str.toCharArray();
char[] revArr = new char[orgArr.length];
for (int i = 0; i < orgArr.length;i++)  {
revArr[i] = orgArr[orgArr.length - 1 - i];
}
String revStr = new String(revArr);
System.out.println(revStr);
Suraj Chandran
Doesn't work for surrogate pairs... Getting used to using libraries is a jolly good idea.
Tom Hawtin - tackline
@tom..I started with.."If you are new to programming..". The whole idea was to simulate learning :)
Suraj Chandran