Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In-line string substitution in Java?

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?

like image 448
tibbon Avatar asked Oct 30 '25 22:10

tibbon


2 Answers

The closest would be something like:

 String s = String.format("The %s took a %s to the %s for a nice %s in the %s", personTitle, modeOfTransit, holidayLocation, verb, noun);
like image 109
prusswan Avatar answered Nov 02 '25 11:11

prusswan


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.)

like image 31
Ted Hopp Avatar answered Nov 02 '25 12:11

Ted Hopp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!