package demo;
public class ReverseString {
public static void main(String[] args) {
String strs="12345ABCD";
StringBuffer sb = new StringBuffer(strs);
String temp = reverseIt(strs);
String temp2 = sb.reverse().toString();//调用StringBuffer自己的字符串反转方法
System.out.println("自己写的reverse后的串是:"+temp);
System.out.println("StringBuffer反转后的串是:"+temp2);
}
//方法一:倒序拼接的方法
public static String reverseIt(String str){
int i;
int len=str.length();
StringBuffer sb = new StringBuffer(len);
for(i=(len-1);i>=0;i--){
sb.append(str.charAt(i));
}
return sb.toString();
}
//方法二:字符串反向拼接的方法
public static String reverseIt2(String s){
int length = s.length();
String reverse = ""; //注意这是空串,不是null
for (int i = 0; i < length; i++)
reverse = s.charAt(i) + reverse;//在字符串前面连接, 而非常见的后面
return reverse;
}
//方法三:利用数组实现
public String reverse(String str) {
if ((null == str) || (str.length() <= 1)) {
return str;
}
char[] chars = str.toCharArray();
int right = chars.length - 1;
for (int left = 0; left < right; left++) {
char swap = chars[left];
chars[left] = chars[right];
chars[right--] = swap;
}
return new String(chars);
}
}