package com.kivkyle.string;
/*
* String字符串的反转
*/
public class StringReverse {
public static void main(String[] args) {
// test
StringReverse sr = new StringReverse();
String str = "我爱祖国";
sr.reverse1(str);
// System.out.println(sr.reverse6(str));
// System.out.println(sr.reverse7(str));
}
public void reverse1(String str) {// 1.通过StringBuffer的reverse()-String
System.out.println(new StringBuffer(str).reverse().toString());
}
public void reverse2(String str) {// 2.StringBuffer的append()方法
char[] c = str.toCharArray();
StringBuffer sb = new StringBuffer();
for (int i = str.length() - 1; i >= 0; i--) {
sb.append(c[i]);
}
System.out.println(sb.toString());
}
public void reverse3(String str) {// 3.通过str-char[]-由后向前遍历数组进行反转-char
char[] c = str.toCharArray();
for (int i = c.length - 1; i >= 0; i--) {
char cc = c[i];
System.out.print(cc);
}
}
public void reverse4(String str) {// 4.String的subString()方法 字符串截取-String
for (int i = str.length() - 1; i >= 0; i--) {
String strRe = str.substring(i, i + 1);
System.out.print(strRe);
}
}
public void reverse5(String str) {// 5.String的charAt()方法-char
for (int i = str.length() - 1; i >= 0; i--) {
char c = str.charAt(i);
System.out.print(c);
}
}
public String reverse6(String str) {// 6.递归-返回String
int i = str.length();
if (i < 1) {
return "";
} else {
String strResult = str.charAt(--i) + reverse6(str.substring(0, i));
return strResult;
}
}
public String reverse7(String str) {// 7.栈-返回String
char[] c = new char[str.length()];// 栈
for (int i = 0; i < str.length(); i++) {// 进栈
c[i] = str.charAt(i);
}
StringBuffer sb = new StringBuffer("");
for (int j = c.length - 1; j >= 0; j--) {
sb.append(c[j]);
}
return sb.toString();
}
}
String字符串反转
最新推荐文章于 2022-02-21 20:11:52 发布