Java将字符串中指定部分进行反转。比如将“abcdefg”反转为”abfedcg”

方式一

@Test
public void show() {
      String s1 = "abcdefg";
      String s2 = "a";
      // 先将需要翻转的字符串给截取出来
      char[] chars = s1.substring(1, 6).toCharArray();
      // 循环截取出来的字符串数组.从后往前循环
      for (int i = chars.length - 1; i >= 0; i--) {
          // 拼接字符串
          s2 = s2 + chars[i];
      }
      s2 += "g";
      System.out.println(s2); //=> afedcbg
}

方式二

@Test
public void show2() {
    String s1 = "abcdefg";
    String s2 = myResover(s1, 1, 6);
    System.out.println(s2); //=> afedcbg
}

// 采用append的方式要比使用 + 拼接效率高
private String myResover(String s1, int startIndex, int endIndex) {
    StringBuilder sb1 = new StringBuilder(s1.length());
    // 添加不反转的字符
    sb1.append(s1.substring(0, startIndex));
    // 获取到要反转的字符串数组
    char[] chars = s1.substring(startIndex, endIndex).toCharArray();
    // 从右往左循环,append到数组中
    for (int i = chars.length - 1; i >= 0; i--) {
        sb1.append(chars[i]);
    }
    // 再将右边不参与反转的字符串添加到数组中
    sb1.append(s1.substring(endIndex));
    return sb1.toString();
}
posted @ 2021-08-03 13:26  Y-X南川  阅读(333)  评论(0编辑  收藏  举报