Java中如何反转Byte数组中的字符顺序?
作者:慢热型
时间:2023-04-25
浏览:1
使用Byte数组packagenet.javaguides.corejava.string;/****@authoryisu**/publicclassReverseStringUsingByteArray{//FunctiontoreverseastringinJavausingbytearraypublicstaticStringreverse(Stringstr){//returnifstringisnulloremptyif(str==null||str.equals(""))returnstr;
本文目录
使用 Byte 数组
package net.javaguides.corejava.string;
/**
*
* @author yisu
*
*/
public class ReverseStringUsingByteArray {
// Function to reverse a string in Java using byte array
public static String reverse(String str) {
// return if string is null or empty
if (str == null || str.equals(""))
return str;
// convert string into bytes
byte[] bytes = str.getBytes();
// start from the two end points l and h of the given string
// and increment l & decrement h at each iteration of the loop
// until two end-points intersect (l >= h)
for (int l = 0, h = str.length() - 1; l < h; l++, h--) {
// Swap values at l and h
byte temp = bytes[l];
bytes[l] = bytes[h];
bytes[h] = temp;
}
// convert byte array back into the string
return new String(bytes);
}
public static void main(String[] args) {
String str = "Java Guides";
// String is immutable
str = reverse(str);
System.out.println("Reverse of the given string is : " + str);
}
}输出:
Reverse of the given string is : sediuG avaJ
作者最新文章
wps表格office打不开怎么办怎么解决
2026-11-03 10:00
ArchiveofOurOwn看文主页入口指南
2026-10-30 10:27
CorelDRAW转曲后如何修改:曲线节点编辑与轮廓调整教程
2026-10-30 09:53
QQ邮箱地址书写时括号能不能添加
2026-10-27 23:17
搭载 RTX 5070 12GB 显卡 联想 Legion 5i 15IAX11 游戏本海外发布
2026-10-26 16:26
下一篇:
liunx php如何安装redis扩展
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多

































