Java是一門面向物件程式語言,不僅吸收了C++語言的各種優點,還摒棄了C++裡難以理解的多繼承、指標等概念,以下是為大家分享的'Java常用字串反轉的五種方案,供大家參考借鑑,歡迎瀏覽!
第一個類是執行類
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);
}
}
}