Java: formatowanie łańcuchów za pomocą symboli zastępczych

Jestem nowy w Javie i jestem z Pythona. W Pythonie formatujemy ciąg znaków w następujący sposób:

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

Jak replikować to samo w Javie?

Author: user1757703, 2013-07-09

3 answers

The MessageFormat klasa wygląda jak to, czego szukasz.

System.out.println(MessageFormat.format("{0} + {1} = {2}", x, y, x + y));
 47
Author: rgettman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-08 22:52:32

Java ma String.format {[4] } metoda, która działa podobnie do tej. Oto przykład, jak z niego korzystać. to jest odniesienie do dokumentacji , które wyjaśnia, czym mogą być wszystkie opcje %.

A oto przykład inlined:

package com.sandbox;

public class Sandbox {

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

To drukuje "jest godzina piąta".

 10
Author: Daniel Kaplan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:16:56

Możesz to zrobić (używając String.format):

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"
 3
Author: jh314,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-08 22:50:35