Heim  >  Artikel  >  Java  >  So kehren Sie Zeichen mithilfe eines Byte-Arrays in Java um

So kehren Sie Zeichen mithilfe eines Byte-Arrays in Java um

WBOY
WBOYnach vorne
2023-04-29 10:49:061367Durchsuche

Byte-Array verwenden

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);
}
}

Ausgabe:

Reverse of the given string is : sediuG avaJ

Das obige ist der detaillierte Inhalt vonSo kehren Sie Zeichen mithilfe eines Byte-Arrays in Java um. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Dieser Artikel ist reproduziert unter:yisu.com. Bei Verstößen wenden Sie sich bitte an admin@php.cn löschen