Java倒弦

示例

您可以通过几种方法来反转字符串以使其向后。

  1. StringBuilder / StringBuffer:

     String code = "code";
    System.out.println(code);
    StringBuilder sb = new StringBuilder(code);
    code = sb.reverse().toString();
    System.out.println(code);
  2. 字符数组:

    String code = "code";
    System.out.println(code);
    char[] array = code.toCharArray();
    for (int index = 0, mirroredIndex =array.length- 1; index < mirroredIndex; index++, mirroredIndex--) {
       char temp = array[index];
       array[index] = array[mirroredIndex];
       array[mirroredIndex] = temp;
    }
    // 反转打印
    System.out.println(new String(array));