ホームページ  >  記事  >  Java  >  Javaでバイト配列を使用して文字を反転する方法

Javaでバイト配列を使用して文字を反転する方法

WBOY
WBOY転載
2023-04-29 10:49:061367ブラウズ

バイト配列を使用

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でバイト配列を使用して文字を反転する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はyisu.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。