Format de chaîne Java ()

La méthode Java String format () renvoie une chaîne formatée en fonction de l'argument passé.

La syntaxe de la format()méthode String est:

 String.format(String format, Object… args)

Ici,

  • format()est une méthode statique. Nous appelons la format()méthode en utilisant le nom de la classe String.
  • dans le code ci-dessus signifie que vous pouvez passer plus d'un objet à format().

Paramètres de format ()

La format()méthode prend deux paramètres.

  • format - une chaîne de format
  • args - 0 ou plus d'arguments

format () Valeur de retour

  • renvoie une chaîne formatée

Exemple 1: format de chaîne Java ()

 class Main ( public static void main(String() args) ( String language = "Java"; int number = 30; String result; // format object as a string result = String.format("Language: %s", language); System.out.println(result); // Language: Java // format number as a hexadecimal number result = String.format("Hexadecimal Number: %x", number); // 1e System.out.println(result); // Hexadecimal Number: 1e ) )

Dans le programme ci-dessus, notez le code

 result = String.format("Language: %s", language);

Voici "Language: %s"une chaîne de format .

%sdans la chaîne de format est remplacé par le contenu de la langue. %sest un spécificateur de format.

De même, %xest remplacé par la valeur hexadécimale du nombre dans String.format("Number: %x", number).

Spécificateurs de format

Voici les spécificateurs de format couramment utilisés:

Prescripteur La description
%b, %B "true"ou "false"basé sur l'argument
%s, %S un string
%c, %C un caractère Unicode
%d un entier décimal (utilisé pour les entiers uniquement)
%o un entier octal (utilisé pour les entiers uniquement)
%x, %X un entier hexadécimal (utilisé pour les entiers uniquement)
%e, %E pour la notation scientifique (utilisée pour les nombres à virgule flottante)
%f pour les nombres décimaux (utilisé pour les nombres à virgule flottante)

Exemple 2: Formatage de chaînes de nombres

 class Main ( public static void main(String() args) ( int n1 = 47; float n2 = 35.864f; double n3 = 44534345.76d; // format as an octal number System.out.println(String.format("n1 in octal: %o", n1)); // 57 // format as hexadecimal numbers System.out.println(String.format("n1 in hexadecimal: %x", n1)); // 2f System.out.println(String.format("n1 in hexadecimal: %X", n1)); // 2F // format as strings System.out.println(String.format("n1 as string: %s", n1)); // 47 System.out.println(String.format("n2 as string: %s", n2)); // 35.864 // format in scientific notation System.out.println(String.format("n3 in scientific notation: %g", n3)); // 4.45343e+07 ) )

Production

 n1 en octal: 57 n1 en hexadécimal: 2f n1 en hexadécimal: 2F n1 en chaîne: 47 n2 en chaîne: 35.864 n3 en notation scientifique: 4.45343e + 07

Vous pouvez utiliser plusieurs spécificateurs de format dans la chaîne de format.

Exemple 3: utilisation de plusieurs spécificateurs de format

 // using more than one format specifiers // in a format string class Main ( public static void main(String() args) ( int n1 = 47; String text = "Result"; System.out.println(String.format("%shexadecimal: %x", text, n1)); ) )

Production

 Résultat hexadécimal: 2f

Ici, %sest remplacé par la valeur du texte. De même, %oest remplacé par la valeur hexadécimale de n1.

Fonctionnement du format Java String ()

Exemple 4: mise en forme de nombres décimaux

 class Main ( public static void main(String() args) ( float n1 = -452.534f; double n2 = -345.766d; // format floating-point as it is System.out.println(String.format("n1 = %f", n1)); // -452.533997 System.out.println(String.format("n2 = %f", n2)); // -345.766000 // show up to two decimal places System.out.println(String.format("n1 = %.2f", n1)); // -452.53 System.out.println(String.format("n2 = %.2f", n2)); // -345.77 ) )

Production

 n1 = -452,533997 n2 = -345,766000 n1 = -452,53 n2 = -345,77

Remarque: lorsque nous formons -452,534 en utilisant %f, nous obtenons -452,533997 . Ce n'est pas à cause de la format()méthode. Java ne renvoie pas la représentation exacte des nombres à virgule flottante.

Lorsque le %.2fspécificateur de format est utilisé, format()donne deux nombres après la virgule décimale.

Exemple 5: Remplir les nombres avec des espaces et 0

 // using more than one format specifiers // in a format string class Main ( public static void main(String() args) ( int n1 = 46, n2 = -46; String result; // padding number with spaces // the length of the string will be 5 result = String.format("|%5d|", n1); // | 46| System.out.println(result); // padding number with numbers 0 // the length of the string will be 5 result = String.format("|%05d|", n1); // |00046| System.out.println(result); // using signs before numbers result = String.format("%+d", n1); // +46 System.out.println(result); result = String.format("%+d", n2); // -46 System.out.println(result); // enclose negative number within parenthesis // and removing the sign result = String.format("%(d", n2); // (46) System.out.println(result); ) )

Exemple 6: Utilisation de 0x et 0 avant hexadécimal et octal

 // using 0x before hexadecimal // using 0 before octal class Main ( public static void main(String() args) ( int n = 46; System.out.println(String.format("%#o", n)); // 056 System.out.println(String.format("%#x", n)); // 0x2e ) )

Format Java String () avec Locale

La format()méthode String a également une autre syntaxe si vous devez travailler avec les paramètres régionaux spécifiés.

 String.format(Locale l, String format, Object… args)

Exemple 7: Utilisation de la langue allemande au format ()

 // to use Locale import java.util.Locale; class Main ( public static void main(String() args) ( int number = 8652145; String result; // using the current locale result = String.format("Number: %,d", number); System.out.println(result); // using the GERMAN locale as the first argument result = String.format(Locale.GERMAN, "Number in German: %,d", number); System.out.println(result); ) )

Production

 Nombre: 8,652,145 Nombre en allemand: 8,652,145

Remarque: en Allemagne, les entiers sont séparés par .au lieu de ,.

Articles intéressants...