2013-07-08 14 views
23

Ich bin neu in Java und bin aus Python. In Python führen wir eine String-Formatierung wie diese aus:Java: String-Formatierung mit Platzhaltern

>>> x = 4 
>>> y = 5 
>>> print("{0} + {1} = {2}".format(x, y, x + y)) 
4 + 5 = 9 
>>> print("{} {}".format(x,y)) 
4 5 

Wie repliziere ich dasselbe in Java?

Antwort

45

Die MessageFormat Klasse sieht aus wie, was Sie nach

System.out.println(MessageFormat.format("{0} + {1} = {2}", x, y, x + y)); 
+1

Mit dem Vorbehalt, dass 'MessageFormat.format' den leeren Platzhalter' {} 'nicht behandelt. –

+0

... und der Vorbehalt, dass, wenn Sie '{' 'verwenden, es die Klammern nicht erkennen wird –

10

Java hat eine String.format Methode, die ähnlich funktioniert. Here's an example of how to use it. Dies ist die documentation reference, die erklärt, was all diese % Optionen sein können.

Und hier ist ein inlined Beispiel:

package com.sandbox; 

public class Sandbox { 

    public static void main(String[] args) { 
     System.out.println(String.format("It is %d oclock", 5)); 
    }   
} 

Diese Drucke "Es ist 5 oclock".

+1

Dieses ''% basierend Zeichenfolge Formatierung ähnelt [im alten Stil. Formatierung] (http://docs.python.org/2/tutorial/inputoutput.html#old-string-formatting) verwendet in Python verwendet OP die [new-style string Formatierung] (http: //docs.python .org/2/library/string.html # formatspec) –

+0

Ah, aus der Frage, ich wusste nicht, dass er so viel Emp hasis bei der Verwendung von geschweiften Klammern. Ich dachte, er wollte nur eine Möglichkeit, einen String zu formatieren, ohne Strings und Variablen miteinander zu verketten. –

+1

Danke für den Kommentar übrigens. Sonst hätte ich nicht verstanden, warum @gerttman so viele Upvotes bekommen hat. –

3

Sie können dies tun (String.format) mit:

int x = 4; 
int y = 5; 

String res = String.format("%d + %d = %d", x, y, x+y); 
System.out.println(res); // prints "4 + 5 = 9" 

res = String.format("%d %d", x, y); 
System.out.println(res); // prints "4 5" 
Verwandte Themen