Java中经常会用到将字符串进行反转的时候,程序员孔乙己总结了7种反转方法,如下:

//方法1 递归方法

 public static String reverse1(String s) {
int length = s.length();
if (length <= 1){
return s;
}
String left = s.substring(0, length / 2);
String right = s.substring(length / 2, length);
return reverse1(right) + reverse1(left);
}

//方法2 通过 charAt(int index)返回char值进行字符串拼接

 public static String reverse2(String s) {
int length = s.length();
String reverse = "";
for (int i = 0; i < length; i++)
reverse = s.charAt(i) + reverse;
return reverse;
}

//方法3 把字符串转换成字符数组倒叙拼接然后返回值

 public static String reverse3(String s) {
char[] array = s.toCharArray();
String reverse = "";
for (int i = array.length - 1; i >= 0; i--)
reverse += array[i];
return reverse;
}

//方法4 调用StringBuffer中的reverse方法

public static String reverse4(String s) {
return new StringBuffer(s).reverse().toString();
}

//方法5 把字符串转换成字符数组首位对调位置

 public static String reverse5(String orig) {
char[] s = orig.toCharArray();
int n = s.length - 1;
int halfLength = n / 2;
for (int i = 0; i <= halfLength; i++) {
char temp = s[i];
s[i] = s[n - i];
s[n - i] = temp;
}
return new String(s);
}

//方法6

public static String reverse6(String s) {
char[] str = s.toCharArray();
int begin = 0;
int end = s.length() - 1;
while (begin < end) {
str[begin] = (char) (str[begin] ^ str[end]);
str[end] = (char) (str[begin] ^ str[end]);
str[begin] = (char) (str[end] ^ str[begin]);
begin++;
end--;
}
return new String(str);
}

//方法7

import java.util.Stack;
public class StringReverse {
public static String reverse7(String s) {
char[] str = s.toCharArray();
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < str.length; i++)
stack.push(str[i]); String reversed = "";
for (int i = 0; i < str.length; i++)
reversed += stack.pop();
return reversed;
}
}

最新文章

  1. ajax 中boolean值技巧
  2. How to Release the Temp LOB Space and Avoid Hitting ORA-1652 (文档 ID 802897.1)
  3. python中函数总结之装饰器闭包
  4. VSPackge插件系列:简单文本编辑器的实现
  5. python 零散记录(三) 格式化字符串 字符串相关方法
  6. 使用XAML在WPF项目中承载ArcGIS Engine地图控件开发
  7. Android minHeight/Width,maxHeight/Width
  8. Dubbo集成步骤
  9. postgresql 在linux上的源码安装
  10. 山谈c中printf格式修饰符
  11. 浅谈viewport
  12. Gradle的一些技巧和遇到的问题
  13. Codeforces 581F Zublicanes and Mumocrates 树形dp
  14. c# 获取端口的连接数,网站的连接数
  15. Oracle表空间迁移Move Tablespace
  16. [JDBC]ORA-01000: 超出打开游标的最大数(ORA-01000: maximum open cursors exceeded)
  17. Python学习——web框架
  18. 【转】DSL
  19. python进行数据分析---python3卡方
  20. Etcd安全配置之Basic Auth认证

热门文章

  1. session安全&amp;&amp;CBC字符反转攻击&amp;&amp;hash拓展攻击
  2. 码云+Git配置仓库
  3. keepalived+nginx集群
  4. LinkedList,ArrayList,HashMap,TreeMap
  5. Apache shiro权限基本使用
  6. 043 01 Android 零基础入门 01 Java基础语法 05 Java流程控制之循环结构 05 do-while循环介绍及应用
  7. Python实现的数据结构与算法之双端队列详解
  8. 用ASP创建API。NET Core (Day2):在ASP中创建API。网络核心
  9. [学习笔记] Treap
  10. LiteOS-任务篇-源码分析-删除任务函数