Maison > Java > javaDidacticiel > Comment inverser les caractères à l'aide d'un tableau d'octets en Java

Comment inverser les caractères à l'aide d'un tableau d'octets en Java

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Libérer: 2023-04-29 10:49:06
avant
1533 Les gens l'ont consulté

Utiliser le tableau d'octets

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);
}
}
Copier après la connexion

Sortie :

Reverse of the given string is : sediuG avaJ
Copier après la connexion

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Étiquettes associées:
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Derniers numéros
Impossible d'installer Java
Depuis 1970-01-01 08:00:00
0
0
0
Java peut-il être utilisé comme backend du Web ?
Depuis 1970-01-01 08:00:00
0
0
0
Installer JAVA
Depuis 1970-01-01 08:00:00
0
0
0
Aide : Données chiffrées JAVA Décryptage PHP
Depuis 1970-01-01 08:00:00
0
0
0
Est-ce en langage Java ?
Depuis 1970-01-01 08:00:00
0
0
0
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal