Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.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/kotlin格式字符串_Java_Kotlin - Fatal编程技术网

使用数组从文件读取的Java/kotlin格式字符串

使用数组从文件读取的Java/kotlin格式字符串,java,kotlin,Java,Kotlin,正如标题所说,我想知道在Java中是否有任何一种使用数组格式化字符串的方法 让我举一个科特林的例子 var sentences = arrayOf("hello", "world") var template = "Dialogue: ${sentences[0]}\n" + "Dialogue: ${sentences[1]}\n" template.format(sentences) print(template) 上述代码运行良好。那么Java呢 编辑

正如标题所说,我想知道在Java中是否有任何一种使用数组格式化字符串的方法

让我举一个科特林的例子

var sentences = arrayOf("hello", "world")
var template = "Dialogue: ${sentences[0]}\n" +
                "Dialogue: ${sentences[1]}\n"

template.format(sentences)

print(template)
上述代码运行良好。那么
Java

编辑 对不起,我没有把我的问题说清楚。当我遇到我的真实案例时,我发现我的代码现在无法为我工作

实际上,
模板
是从文件中读取的

var sentences = arrayOf("hello", "world")
var template = File("template.txt").readText()

template.format(sentences)
print(template)
template.txt文件包含:

Dialogue: ${sentences[0]}
Dialogue: ${sentences[1]}
如您所见,我想读取文件,然后格式化结果。

此外,我对这个问题感到非常抱歉因为它似乎被更改为如何格式化从文件读取的字符串。

您可以使用:


上面的代码完全错误地使用了
String.format
。让我解释一下原因

在前两行:

var sentences = arrayOf("hello", "world")
var template = "Dialogue: ${sentences[0]}\n" +
              "Dialogue: ${sentences[1]}\n"
这里,
模板
已经存在,它是一个
字符串
,它的值是
“Dialogue:hello\nDialogue:world”
,这是您看到的结果

如果您不信任我,请尝试用不存在的变量名替换
句子。您将得到一个编译错误,因为在创建字符串时,字符串是完全连接的。“字符串模板”只是
+
的语法糖

然后,调用了
template.format
,它实际上是
String.format
,返回的字符串不被使用

因为这在Kotlin中已经是错误的,所以您可以轻松地在Java中执行相同的操作:

String[] sentences = new String { "hello", "world" };
String template = "Dialogue: " + sentences[0] + "\n" +
                  "Dialogue: " + sentences[1] + "\n";

template.format(sentences);

System.out.print(template);
此代码等于您给出的Kotlin代码

我猜你想要这个:

String template = String.format("Dialogue: %s%nDialogue: %s%n", sentences);
System.out.print(template);

使用
%s
替换模板文件中的内容。 Kotlin(Java)随后将为每个参数调用
toString
方法,并根据参数的顺序替换它们

//template.txt
%s magnificent %s!

//Main.kt
val sentences = arrayOf("hello", "world")
val template = File("template.txt").readText()

template.format(sentences)
print(template)
输出:

hello magnificent world!

为什么关闭我的问题可能重复?你读过我的问题了吗?@Phil你能再读一遍我的问题吗?根据你的编辑,这是一个非常复杂的问题..带有数组的OPs示例更类似于
MessageFormat
@Phil我不知道这个类。不过,如果这个答案对任何人都有帮助的话,我将把它留给大家。在我看来,使用直接字符串连接比依赖格式字符串更容易阅读。编译器将使用
StringBuilder
@BrianGordon自动优化它,这也很有趣。我对Java不太熟悉,我想我需要学习这些实用程序类(例如,
MessageFormat
StringBuilder
他确实使用了它,
template.format
String.format
相同。这是一个答案吗?(这也有点粗鲁)我已经发布了答案。@JonathanLamI看不出这与我的答案有什么不同。我已经给出了一个理想的方法(和你一样)和他的例子相同的方法(你没有)。你是对的。但我会告诉你为什么我应该这样做。
hello magnificent world!