如何在 Scala 中进行字符串连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30515504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to do string concatenation in Scala
提问by Rubbic
I have the following code that based on the input (args) I want to create a string but the answer is incorrect. I have args(0) is a path, args(1) is an operand like "+", and args(2) is a number (and I want to put space between them:
我有以下基于输入(args)的代码我想创建一个字符串,但答案不正确。我有 args(0) 是一个路径,args(1) 是一个像“+”这样的操作数,而 args(2) 是一个数字(我想在它们之间加空格:
//some code ..
var Statement=""
for (j<-0 to 2)
{
if (Files.exists(Paths.get(args(j)))){
Statement.concat(inputXml)
Statement.concat(" ")
}
else{
Statement.concat(args(j))
Statement.concat(" ")
}
println(args(j))
println(Statement)
}
println(Statement)
//some code ...
the output is a blank! I have used this link as reference. Would you please help me on this I am new in Scala. Thanks.
输出为空白!我已使用此链接作为参考。你能帮我解决这个问题吗?我是 Scala 的新手。谢谢。
回答by Karl
String.concat returns an entirely new String object. It will not mutate your current Statement variable at all. Now I wouldn't recommend you do the following, but all you technically need to change is reassign Statement to the return value of all your concat calls:
String.concat 返回一个全新的 String 对象。它根本不会改变您当前的 Statement 变量。现在我不建议您执行以下操作,但您在技术上需要更改的只是将 Statement 重新分配给所有 concat 调用的返回值:
//some code ..
var Statement=""
for (j<-0 to 2)
{
if (Files.exists(Paths.get(args(j)))){
Statement = Statement.concat(inputXml)
Statement = Statement.concat(" ")
}
else{
Statement = Statement.concat(args(j))
Statement = Statement.concat(" ")
}
println(args(j))
println(Statement)
}
println(Statement)
//some code ...
A more performant solution would be to use a StringBuilderinstead.
一个更高效的解决方案是使用StringBuilder代替。
val Statement = StringBuilder.newBuilder
Statement.append(...)
println(Statement.toString)

