Formatting strings in Java

I used python all too often and I forgot if there is a way to do this in Java:

print "I am a %s" % string

I googled, but it’s hard to find simple things like this when you don’t know exactly what it is called in every language.

+3
source share
3 answers

Two possible simple ways to do this:

String yourStringHere = "human";
System.out.println(String.format("I am a %s", yourStringHere));

or

System.out.printf("I am a %s\n", yourStringHere);

Note that printf()it will not print a new line, so you need to add it manually ("\ n"). But (thanks to BalusC) you can also use it "%n"in your format. It will be replaced by the default newline character. (For So: String.format("I am a %s%n", yourString))
Both print I am a human\n.

In Java it is called formatting. Take a look String.format().

+10
System.out.println( "I am a " + string );

:

System.out.println( String.format( "I am a %s", string ) );
+4

MessageFormat.format() , % s {0} ( ).

System.out.print(MessageFormat.format("I am a {0}", string));

If you ever want to localize your program, this is the best way (or, worse, depending on what you want to achieve), because it will automatically use localized formats.

+2
source

Source: https://habr.com/ru/post/1767605/


All Articles