2011-12-26 101 views
2

我在Processing中做了一些工作,基本上是Java。我通常只在Ruby中工作,而且我已經習慣了很多相當優雅和漂亮的代碼約定。Java中的內聯字符串替換?

如果我有一個字符串,我想插入其他字符串,在Java中執行它最美麗的方法是什麼?

在Ruby中,我做這樣的事情一般(其中每個變量是一個字符串):

p "The #{person_title} took a #{mode_of_transit} to the #{holiday_location} for a nice #{verb} in the #{noun}" 

這樣看來在Java中,我需要手動將它們連接起來是這樣的:

println("The " + personTitle + " took a " + modeOfTransit + " to the " holidayLocation + for a nice " + verb + " in the " + noun) 

這只是感覺不對我。它的工作原理,但它不光滑。有沒有辦法在Java中做到這一點?

+0

您可以使用String.format:http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#format(java.lang.String,java.lang。對象......)我只是覺得很亂。 – eboix 2011-12-26 03:28:16

回答

7

最接近的將是這樣的:

String s = String.format("The %s took a %s to the %s for a nice %s in the %s", personTitle, modeOfTransit, holidayLocation, verb, noun); 
0

您可以使用System.out.format()方法格式化字符串寫入System.out或使用靜態方法String.format.有關格式的更多細節格式的字符串讀this文章。

System.out.format("The %s took a %s to the %s for a nice %s in the %s", 
     personTitle, modeOfTransit, holidayLocation, verb, noun); 
0

您可以使用System.out.printf(同System.out.format)和format string"%s"是一個字符串格式說明)同時使它看起來更加流暢,並且可以按照自己想要的方式格式化輸出。

還有String.format返回格式String,而不是必須打印它(如C中的sprintf)。