Reverse a string in Java
I have "Hello World"
kept in a String variable named hi
.
I need to print it, but reversed.
How can I do this? I understand there is some kind of a function already built-in into Java that does that.
Related: Reverse each individual word of “Hello World” string with Java
You can use this:
new StringBuilder(hi).reverse().toString()
Or, for versions earlier than JDK 1.5, use java.util.StringBuffer
instead of StringBuilder
— they have the same API. Thanks commentators for pointing out that StringBuilder
is preferred nowadays.
对于不允许使用StringBuilder
或StringBuffer
Online Judge问题 ,您可以使用char[]
代替它,如下所示:
public static String reverse(String input){
char[] in = input.toCharArray();
int begin=0;
int end=in.length-1;
char temp;
while(end>begin){
temp = in[begin];
in[begin]=in[end];
in[end] = temp;
end--;
begin++;
}
return new String(in);
}
public static String reverseIt(String source) {
int i, len = source.length();
StringBuilder dest = new StringBuilder(len);
for (i = (len - 1); i >= 0; i--){
dest.append(source.charAt(i));
}
return dest.toString();
}
http://www.java2s.com/Code/Java/Language-Basics/ReverseStringTest.htm
链接地址: http://www.djcxy.com/p/70448.html上一篇: 有人可以彻底解释一下URI是什么吗?
下一篇: 在Java中反转字符串