I got asked a question recently about reversing a string in java. The first thing that came to my mind was to use ruby to solve the problem since there is a reverse method on the string object in ruby.
Since I love java so much, I would like to discuss a solution in java. My first solution was something like this below:
static String reverse(String str){
int i, len = str.length();
StringBuilder dest = new StringBuilder(len);
for (i = (len - 1); i >= 0; i--)
dest.append(str.charAt(i));
return dest.toString();
}
I later discovered that the StringBuffer and StringBuilder classes have a reverse method also like the ruby string implementation. Therefore, you can solve the problem using the code below:
static String reverse(String str){
return new StringBuilder(str).reverse().toString();
}
One would think that the string class in java should contain this method but it does not. I wonder if it could be added in openjdk or something. Your thoughts are welcomed.