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
作者最新文章
漫蛙manwa漫画链接分享及官网指南
2026-11-21 10:11
Opera欧朋浏览器垂直标签栏怎么开启 三种入口设置步骤
2026-11-20 14:10
AO3官网镜像链接一键跳转-手机入口快速访问
2026-11-19 15:27
AO3镜像站入口及官网导航链接
2026-11-18 11:01
WPS的Excel用Office打开无法显示照片
2026-11-08 14:31
下一篇:
liunx php如何安装redis扩展
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多

































