public void convertStr(String str){
成都創(chuàng)新互聯(lián)公司主要從事成都做網(wǎng)站、成都網(wǎng)站設(shè)計、網(wǎng)頁設(shè)計、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務(wù)。立足成都服務(wù)雄縣,十年網(wǎng)站建設(shè)經(jīng)驗,價格優(yōu)惠、服務(wù)專業(yè),歡迎來電咨詢建站服務(wù):13518219792
//將String 對象轉(zhuǎn)換為可改變的StringBuffer類對象
//然后調(diào)用StringBuffer類的reverse()方法實現(xiàn)反轉(zhuǎn)
String strReverse=new StringBuffer(str).reverse().toString();
System.out.println(strReverse);
}
我們可以通過運用JAVA的?StringBuffer的1字符串反轉(zhuǎn)方法直接置逆,下面將舉例說明:
public?class?Test?{
public?static?void?main(String[]?args){
String?str?=?"12345678";
System.out.println(str);
//聲明一個緩沖字符串
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("對字符串進行反轉(zhuǎn)操作后為:"+s2);
StringBuffer sb=new StringBuffer("abcdefg");
StringBuffer sb2=sb.reverse();
System.out.println("對StringBuffer進行反轉(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]+" ");
}
}
}
當(dāng)前標題:字符串反轉(zhuǎn)java代碼 字符串反轉(zhuǎn)java方法
轉(zhuǎn)載注明:http://jinyejixie.com/article2/dosdeoc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供營銷型網(wǎng)站建設(shè)、網(wǎng)站改版、網(wǎng)頁設(shè)計公司、網(wǎng)站導(dǎo)航、建站公司、
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)