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公式编辑器 功能入口与编辑技巧
2026-11-04 16:38
动漫共和国漫画全站直达链接
2026-11-04 12:05
wps表格office打不开怎么办怎么解决
2026-11-03 10:00
ArchiveofOurOwn看文主页入口指南
2026-10-30 10:27
CorelDRAW转曲后如何修改:曲线节点编辑与轮廓调整教程
2026-10-30 09:53
下一篇:
liunx php如何安装redis扩展
热门文章
更多
精品专题
更多
Mac软件
更多
火山引擎 网页版
Windows/ macOS/ Linux
火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。
















