我有“Hello World”保存在一个名为hi的字符串变量中。

我需要打印出来,但要颠倒过来。

我该怎么做呢?我知道Java中已经内置了这样一个函数。

相关:用Java反向“Hello World”字符串的每一个单词


当前回答

以上所有的解决方案都太好了,但在这里,我正在使用递归编程制作反向字符串。

这对于寻找递归方法做反向字符串的人是有帮助的。

public class ReversString {

public static void main(String args[]) {
    char s[] = "Dhiral Pandya".toCharArray();
    String r = new String(reverse(0, s));
    System.out.println(r);
}

public static char[] reverse(int i, char source[]) {

    if (source.length / 2 == i) {
        return source;
    }

    char t = source[i];
    source[i] = source[source.length - 1 - i];
    source[source.length - 1 - i] = t;

    i++;
    return reverse(i, source);

}

}

其他回答

过程:

我们可以使用split()来拆分字符串。然后使用反向循环并添加字符。


代码片段:

class test
{
  public static void main(String args[]) 
  {
      String str = "world";
      String[] split= str.split("");

      String revers = "";
      for (int i = split.length-1; i>=0; i--)
      {
        revers += split[i];
      }
      System.out.printf("%s", revers);
   }  
}

 //output : dlrow

public class Test {

public static void main(String args[]) {
   StringBuffer buffer = new StringBuffer("Game Plan");
   buffer.reverse();
   System.out.println(buffer);
 }  
}
StringBuilder s = new StringBuilder("racecar");
    for (int i = 0, j = s.length() - 1; i < (s.length()/2); i++, j--) {
        char temp = s.charAt(i);
        s.setCharAt(i, s.charAt(j));
        s.setCharAt(j, temp);
    }

    System.out.println(s.toString());

它会得到你输入的值,并反向返回;)

public static  String reverse (String a){
    char[] rarray = a.toCharArray();
    String finalvalue = "";
    for (int i = 0; i < rarray.length; i++)
    {
        finalvalue += rarray[rarray.length - 1 - i];
    }   
return finalvalue;

}

使用apache.commons.lang3

StringUtils.reverse(hi)