Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java中的行内字符串替换?_Java_Ruby_String_Concatenation_Processing - Fatal编程技术网

Java中的行内字符串替换?

Java中的行内字符串替换?,java,ruby,string,concatenation,processing,Java,Ruby,String,Concatenation,Processing,我正在做一些处理方面的工作,基本上是Java。我通常只在Ruby中工作,我已经习惯了很多相当优雅和漂亮的代码约定 如果我有一个字符串要插入其他字符串,那么在Java中最漂亮的方法是什么 在Ruby中,我通常会这样做(其中每个变量都是一个字符串): 在Java中,我需要像这样手动连接它们: println("The " + personTitle + " took a " + modeOfTransit + " to the " holidayLocation + for a nice " + v

我正在做一些处理方面的工作,基本上是Java。我通常只在Ruby中工作,我已经习惯了很多相当优雅和漂亮的代码约定

如果我有一个字符串要插入其他字符串,那么在Java中最漂亮的方法是什么

在Ruby中,我通常会这样做(其中每个变量都是一个字符串):

在Java中,我需要像这样手动连接它们:

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

我觉得这不对。它能工作,但就是不顺畅。有没有一种在Java中实现这一点的方法

您可以使用
System.out.format()
方法将格式化字符串写入
System.out
中,或者使用静态方法
string.format格式化字符串。
有关格式化的详细信息,请阅读本文


看看构建格式化字符串或直接格式化和打印的方法。(
System.out
是一个
PrintStream

最接近的是:

 String s = String.format("The %s took a %s to the %s for a nice %s in the %s", personTitle, modeOfTransit, holidayLocation, verb, noun);
您可以使用(
System.out.format
)和(
“%s”
是字符串的格式说明符)使其看起来更流畅,也可以按您想要的方式格式化输出

还有一个
String.format
返回格式化的
String
,而不必打印它(就像C中的
sprintf

你可以使用String.format:,java.lang.Object…),不过我觉得很混乱。
System.out.format("The %s took a %s to the %s for a nice %s in the %s",
         personTitle, modeOfTransit, holidayLocation, verb, noun);
 String s = String.format("The %s took a %s to the %s for a nice %s in the %s", personTitle, modeOfTransit, holidayLocation, verb, noun);