将字符串反转的 Java 方法
2024-08-26 22:23:22
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;
}
}
最新文章
- ajax 中boolean值技巧
- How to Release the Temp LOB Space and Avoid Hitting ORA-1652 (文档 ID 802897.1)
- python中函数总结之装饰器闭包
- VSPackge插件系列:简单文本编辑器的实现
- python 零散记录(三) 格式化字符串 字符串相关方法
- 使用XAML在WPF项目中承载ArcGIS Engine地图控件开发
- Android minHeight/Width,maxHeight/Width
- Dubbo集成步骤
- postgresql 在linux上的源码安装
- 山谈c中printf格式修饰符
- 浅谈viewport
- Gradle的一些技巧和遇到的问题
- Codeforces 581F Zublicanes and Mumocrates 树形dp
- c# 获取端口的连接数,网站的连接数
- Oracle表空间迁移Move Tablespace
- [JDBC]ORA-01000: 超出打开游标的最大数(ORA-01000: maximum open cursors exceeded)
- Python学习——web框架
- 【转】DSL
- python进行数据分析---python3卡方
- Etcd安全配置之Basic Auth认证
热门文章
- session安全&;&;CBC字符反转攻击&;&;hash拓展攻击
- 码云+Git配置仓库
- keepalived+nginx集群
- LinkedList,ArrayList,HashMap,TreeMap
- Apache shiro权限基本使用
- 043 01 Android 零基础入门 01 Java基础语法 05 Java流程控制之循环结构 05 do-while循环介绍及应用
- Python实现的数据结构与算法之双端队列详解
- 用ASP创建API。NET Core (Day2):在ASP中创建API。网络核心
- [学习笔记] Treap
- LiteOS-任务篇-源码分析-删除任务函数