Java中如何反转Byte数组中的字符顺序?
作者:慢热型
时间:2023-04-24
来源:互联网
浏览:0
使用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
作者最新文章
网易2026年Q2财报:营收301亿元,游戏收入增10%,三款重点新游披露进展
2026-09-08 17:51
PDF怎么添加页码?页码位置和起始页怎么设置?
2026-09-03 09:11
图片文件怎么转换成PDF?多张图片如何按顺序合成?
2026-09-02 19:33
CorelDRAW绘制正弦曲线的两种方法:贝塞尔工具与变形工具
2026-09-02 16:08
Excel工作表制作教程:设计易填写、易统计的业务表
2026-09-02 12:11
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多
Windows 10
Windows
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式
Windows/macOS/Linux
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















