商城首页欢迎来到中国正版软件门户

您的位置:首页 > 编程开发 >Java中如何反转Byte数组中的字符顺序?

Java中如何反转Byte数组中的字符顺序?

  发布于2023-04-25 阅读(0)

扫一扫,手机访问

使用 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
本文转载于:https://www.yisu.com/zixun/592468.html 如有侵犯,请联系admin@zhengruan.com删除

热门关注