Java常用字符串反转的五种方案
- java语言
- 关注:2.12W次
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);
}
}
}
- 文章版权属于文章作者所有,转载请注明 https://xuezhezhai.com/jsj/java/z46pd2.html