String字符串反转


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();
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值