public void convertStr(String str){
成都創(chuàng)新互聯(lián)公司主要從事成都做網(wǎng)站、成都網(wǎng)站設(shè)計(jì)、網(wǎng)頁設(shè)計(jì)、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務(wù)。立足成都服務(wù)雄縣,十年網(wǎng)站建設(shè)經(jīng)驗(yàn),價(jià)格優(yōu)惠、服務(wù)專業(yè),歡迎來電咨詢建站服務(wù):13518219792
//將String 對象轉(zhuǎn)換為可改變的StringBuffer類對象
//然后調(diào)用StringBuffer類的reverse()方法實(shí)現(xiàn)反轉(zhuǎn)
String strReverse=new StringBuffer(str).reverse().toString();
System.out.println(strReverse);
}
我們可以通過運(yùn)用JAVA的?StringBuffer的1字符串反轉(zhuǎn)方法直接置逆,下面將舉例說明:
public?class?Test?{
public?static?void?main(String[]?args){
String?str?=?"12345678";
System.out.println(str);
//聲明一個(gè)緩沖字符串
StringBuffer?sb?=?new?StringBuffer(str);
//通過reverse()反轉(zhuǎn)方法,反轉(zhuǎn);然后轉(zhuǎn)換成字符串
str?=?sb.reverse().toString();
System.out.println(str);
}
}
public AbstractStringBuilder reverse() {
boolean hasSurrogate = false;
int n = count - 1;
for (int j = (n-1) 1; j = 0; --j) {
char temp = value[j];
char temp2 = value[n - j];
if (!hasSurrogate) {
hasSurrogate = (temp = Character.MIN_SURROGATE temp = Character.MAX_SURROGATE)
|| (temp2 = Character.MIN_SURROGATE temp2 = Character.MAX_SURROGATE);
}
value[j] = temp2;
value[n - j] = temp;
}
if (hasSurrogate) {
// Reverse back all valid surrogate pairs
for (int i = 0; i count - 1; i++) {
char c2 = value[i];
if (Character.isLowSurrogate(c2)) {
char c1 = value[i + 1];
if (Character.isHighSurrogate(c1)) {
value[i++] = c1;
value[i] = c2;
}
}
}
}
return this;
}
這就是StringBuffer類中reverse方法的源代碼.這就是原理!
package string;
public class StringTest3 {
public static void main(String[] args)
{
String s="abcdefg";
String s2="";
char[] cs=s.toCharArray();
for(int i=cs.length-1;i=0;i--)
{
s2=s2+cs[i];
}
System.out.println("對字符串進(jìn)行反轉(zhuǎn)操作后為:"+s2);
StringBuffer sb=new StringBuffer("abcdefg");
StringBuffer sb2=sb.reverse();
System.out.println("對StringBuffer進(jìn)行反轉(zhuǎn)操作后為:"+sb2);
}
}
反轉(zhuǎn):
public class test{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("請輸入:");
String s1 = input.nextLine();//得到輸入的字符e5a48de588b6e799bee5baa6e997aee7ad9431333363396464串
System.out.print("翻轉(zhuǎn)后:");
for(int i=s1.length()-1;i=0;i--){
System.out.print(s1.charAt(i));
}
}
}
或者
import java.util.*;
public class StringChange{
public static void main(String[] args){
System.out.println("Please enter the String:");
String str = new Scanner(System.in).nextLine(); //輸入字符串
String s2[] = str.split("\\s"); // \s 以空格為分隔符拆分字符串,并保存到數(shù)組s2里面
for (int i = s2.length-1; i = 0; i--) { //反向輸出數(shù)組
System.out.print(s2[i]+" ");
}
}
}