使用 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
以上是java如何使用Byte数组反转字符的详细内容。更多信息请关注PHP中文网其他相关文章!