當前位置:才華齋>IT認證>JAVA認證>

Java常用字串反轉的五種方案大綱

JAVA認證 閱讀(5K)

java程式中如何一個字串進行反轉?或者在字串中指定部分進行反轉的方法有哪些?為幫助大家解決這個疑問,yjbys小編為同學們分享最新Java常用字串反轉的五種方案,快來看看吧!

Java常用字串反轉的五種方案大綱

Java常用字串反轉的5種方案,程式碼如下:

  第一個類是執行類

package everse;

import ner;

public class Run {

public Run() {

t("請輸入一個字串:");

Scanner sc = new Scanner();

String str = ();

tln();

String reversedStrByArray = new Reverse(str)rseByArray();

tln("對應反轉字串為[Array]:"+ reversedStrByArray);

String reversedStrByStack = new Reverse(str)rseByStack();

tln("對應反轉字串為[Stack]:"+ reversedStrByStack);

String reversedStrBySort = new Reverse(str)rseBySort();

tln("對應反轉字串為[逆序遍歷]:"+ reversedStrBySort);

String reversedStrByBit = new Reverse(str)rseByBit();

tln("對應反轉字串為[位運算]:"+ reversedStrByBit);

String reversedStrByRecursive = new Reverse(str)rseByRecursive(str);

tln("對應反轉字串為[遞迴]:"+ reversedStrByRecursive); }

public static void main(String[] args) {

new Run();

}

}

  第二段程式碼是實現類

package everse;

import k;

public class Reverse {

String str = new String();

public Reverse(String str) {

= str;

}

//用陣列實現

public String reverseByArray() {

if(str == null th() == 0) {

return str;

}

int len = th();

char[] chArray = arArray();

for(int i= 0; i< len/2; i++) {

char temp;

temp = chArray[i];

chArray[i] = chArray[len- 1- i];

chArray[len- 1- i] = temp;

}

return new String(chArray);

}

//用棧實現

public String reverseByStack() {

if(str == null th() == 0) {

return str;

}

Stack strStack = new Stack();

char[] chArray = arArray();

for(Character ch: chArray) {

(ch);

}

int len = th();

for(int i= 0; i< len; i++) { chArray[i] = ();

}

return new String(chArray);

}

//用逆序遍歷實現

public String reverseBySort() {

if(str == null th() == 0) {

return str;

}

StringBuilder sb = new StringBuilder();

for(int i= th()- 1; i>= 0; i--) {

nd(At(i));

}

return ring();

}

//用位運算實現

public String reverseByBit() {

if(str == null th() == 0) {

return str;

}

char[] chArray = arArray();

int len = th();

for(int i= 0; i< len/ 2; i++) {

chArray[i]^= chArray[len- 1- i];

chArray[len- 1- i]^= chArray[i];

chArray[i]^= chArray[len- 1- i];

}

return new String(chArray);

}

//用遞迴實現

public String reverseByRecursive(String str) {

if(str == null th() == 0) {

return str;

}

int len = th();

if(len == 1) {

return str;

} else {

return reverseByRecursive(tring(1))+ At(0);

}

}

}