说明:将"abcdef"反转成"fedcba"
package com.tarena.fly;
import org.junit.Test;
/**
* \* Created with IntelliJ IDEA.
* \* User: 武健
* \* Date: 2018/1/29
* \* Time: 20:45
* \* To change this template use File | Settings | File Templates.
* \* Description:String 字符串 反转
* \
*/
public class Main {
/**
* 方法1:利用jdk提供的方法
*/
@Test
public void TestString1() {
String a = "abcdef";
StringBuilder builder = new StringBuilder(a);
String result = builder.reverse().toString();
System.out.println(result);
}
/**
* 方法2 递归
* 将字符串转换成字符数组,对数组进行反转,再将反转后的数组转化成字符串。
*/
@Test
public void TestString2() {
String abc = reverseStr("abcdef");
System.out.println(abc);
}
public String reverseStr(String str) {
if (str.length() <= 1) {
return str;
}
return reverseStr(str.substring(1)) + str.charAt(0);
}
/**
* 方法3 字符串转数组
*/
@Test
public void TestString3() {
String a = "abcdef";
char[] arr = a.toCharArray();
String resuslt = "";
for (int i = arr.length - 1; i >= 0; i--) {
resuslt = resuslt + arr[i];
}
System.out.println(resuslt);
}
}