这是一个老面试题了,可能因为有段时间没写代码的原因吧,竟然被问懵逼了,真是可耻。
String类型数据是java中最长使用的数据之一,区别去其他基础类型的数据(byte、short、int、long、float、double、char、boolean),String类型的数据是引用类型的。
String相关类继承关系:
言归正传:
public class FlashBackTest {
public static void main(String[] args) {
String val = method1("123456789");
System.out.println("方法一:"+val);
String val2 = method2(val);
System.out.println("方法二:"+val2);
String val3 = method3(val2);
System.out.println("方法三:"+val3);
String val4 = method4(val3);
System.out.println("方法四:"+val4);
}
//方法一
public static String method1(String str){
char [] strArr = str.toCharArray();
for(int i=0,j=strArr.length-1;i<j;i++,j--){
char tmp = strArr[i];
strArr[i] = strArr[j];
strArr[j] = tmp;
}
return new String(strArr);
}
//方法二
public static String method2(String str){
StringBuilder sbr = new StringBuilder(str);
StringBuilder val = sbr.reverse();
return val.toString();
}
//方法三
public static String method3(String str){
String num = "";
for(int i = str.length()-1;i>=0;i--){
num = num + str.charAt(i);
}
return num;
}
//方法四
public static String method4(String str){
StringBuilder stringBuilder = new StringBuilder();
for(int i = str.length()-1;i>=0;i--){
stringBuilder.append(str.charAt(i));
}
return stringBuilder.toString();
}
}
方法一:
这种方法类似于二分查找算法,找到字符串的中间值,两两互换;
方法二:
这种方法借助于StringBuilder类提供的reverse()方法进行直接输出反转后的值,StringBuilder同样也可以得到相应的效果,但是reverse方法并不是由StringBuilder和StringBuilder提供的,而是由他们的父类AbstractStringBuilder的抽象类来具体的实现的;
/**
* Causes this character sequence to be replaced by the reverse of
* the sequence. If there are any surrogate pairs included in the
* sequence, these are treated as single characters for the
* reverse operation. Thus, the order of the high-low surrogates
* is never reversed.
*
* Let <i>n</i> be the character length of this character sequence
* (not the length in {@code char} values) just prior to
* execution of the {@code reverse} method. Then the
* character at index <i>k</i> in the new character sequence is
* equal to the character at index <i>n-k-1</i> in the old
* character sequence.
*
* <p>Note that the reverse ope