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

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

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

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


当前回答

我尝试了,只是为了好玩,通过使用一个堆栈。下面是我的代码:

public String reverseString(String s) {
    Stack<Character> stack = new Stack<>();
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < s.length(); i++) {
        stack.push(s.charAt(i));
    }
    while (!stack.empty()) {
        sb.append(stack.pop());
    }
    return sb.toString();

}

其他回答

import java.util.Scanner;

public class Test {

    public static void main(String[] args){
        Scanner input = new Scanner (System.in);
        String word = input.next();
        String reverse = "";
        for(int i=word.length()-1; i>=0; i--)
            reverse += word.charAt(i);
        System.out.println(reverse);        
    }
}

如果你想使用一个简单的for循环!

public class Test {

public static void main(String args[]) {
   StringBuffer buffer = new StringBuffer("Game Plan");
   buffer.reverse();
   System.out.println(buffer);
 }  
}

你也可以试试这个:

public class StringReverse {
    public static void main(String[] args) {
        String str = "Dogs hates cats";
        StringBuffer sb = new StringBuffer(str);
        System.out.println(sb.reverse());
    }
}

它是非常简单的在最少的代码行

public class ReverseString {
    public static void main(String[] args) {
        String s1 = "neelendra";
        for(int i=s1.length()-1;i>=0;i--)
            {
                System.out.print(s1.charAt(i));
            }
    }
}

正如其他人指出的那样,首选的方法是使用:

new StringBuilder(hi).reverse().toString()

但如果你想自己实现这个,恐怕其余的回答都有缺陷。

原因是String表示Unicode点的列表,根据变长编码:UTF-16编码在char[]数组中。

这意味着一些代码点使用数组的单个元素(一个代码单元),但其他代码点使用其中的两个,因此可能会有一对字符必须被视为单个单元(连续的“高”和“低”代理)。

public static String reverseString(String s) {
    char[] chars = new char[s.length()];
    boolean twoCharCodepoint = false;
    for (int i = 0; i < s.length(); i++) {
        chars[s.length() - 1 - i] = s.charAt(i);
        if (twoCharCodepoint) {
            swap(chars, s.length() - 1 - i, s.length() - i);
        }
        twoCharCodepoint = !Character.isBmpCodePoint(s.codePointAt(i));
    }
    return new String(chars);
}

private static void swap(char[] array, int i, int j) {
    char temp = array[i];
    array[i] = array[j];
    array[j] = temp;
}

public static void main(String[] args) throws Exception {
    FileOutputStream fos = new FileOutputStream("C:/temp/reverse-string.txt");
    StringBuilder sb = new StringBuilder("Linear B Syllable B008 A: ");
    sb.appendCodePoint(65536); //http://unicode-table.com/es/#10000
    sb.append(".");
    fos.write(sb.toString().getBytes("UTF-16"));
    fos.write("\n".getBytes("UTF-16"));
    fos.write(reverseString(sb.toString()).getBytes("UTF-16"));
}