I'm doing some work in Processing, which is basically Java. I normally do only work in Ruby and I've gotten used to a lot of the fairly elegant and beautiful code conventions there.
If I have a string that I'd like to insert other strings into, what's the most beautiful way to do it in Java?
In Ruby, I do something like this generally (where each variable is a string):
p "The #{person_title} took a #{mode_of_transit} to the #{holiday_location} for a nice #{verb} in the #{noun}"
It would appear in Java that I need to manually concatenate them like this:
println("The " + personTitle + " took a " + modeOfTransit + " to the " holidayLocation + for a nice " + verb + " in the " + noun)
This just feels wrong to me. It works, but it just isn't smooth. Is there a way to do this in Java?
最接近的是:
String s = String.format("The %s took a %s to the %s for a nice %s in the %s", personTitle, modeOfTransit, holidayLocation, verb, noun);
Take a look at the String.format() method for building a formatted string, or PrintStream.format() for formatting and printing directly. ( System.out
is a PrintStream
.)
You may use System.out.format()
method to write formatted string to System.out
or format a string using the static method String.format.
For more details on formatting read this article.
System.out.format("The %s took a %s to the %s for a nice %s in the %s",
personTitle, modeOfTransit, holidayLocation, verb, noun);
You can use System.out.printf
(same as System.out.format
) and a format string ( "%s"
is the format specifier for a string) to both make it look more fluid and also format your output the way you want.
There's also String.format
that returns the formatted String
, rather than having to print it (like sprintf
in C).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.