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
作者最新文章
CPU硅脂涂抹方法图解及正确操作步骤
2026-09-22 15:23
网易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
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多


































