连接填充字符串

Alv*_*uez 14 string scala

我有三个字符串,例如"A","B","C".我必须生成串联它们的字符串,只有第二个字符串必须用空格填充给定长度.

这是我在直觉和一般Scala新闻的指导下的第一次尝试:

val s1 = "A"
val s2 = "B"
val s3 = "C"
val padLength = 20

val s = s1 + s2.padTo(padLength, " ") + s3
Run Code Online (Sandbox Code Playgroud)

这是错误的,因为padTo返回一个SeqLike,其toString不返回内部的字符串,而是类似Vector的表示.

在Scala中执行此操作的最佳惯用方法是什么?

gou*_*ama 23

String可以(通过隐式转换到StringOps这里)被视为一个字符集合,所以你的填充应该是:

val s = s1 + s2.padTo(padLength, ' ') + s3 // note the single quotes: a char
Run Code Online (Sandbox Code Playgroud)

调用.padTo(padLength, " ")String的实际返回Seq[Any],因为你最终在你的序列在两个字符和字符串.


Dan*_*ral 9

你没有说你是想要向左还是向右填充.只需使用格式:

val s = f"$s1%s$s2%20s$s3"
Run Code Online (Sandbox Code Playgroud)

或者,在Scala 2.10之前(或者如果您需要"20"作为参数):

val s = "%s%"+padLength+"s%s" format (s1, s2, s3)
Run Code Online (Sandbox Code Playgroud)

使用负填充向右侧而不是左侧添加填充空间.


som*_*ytt 5

有人应该提一下你应该发出警告:

apm@mara:~$ skala -Ywarn-infer-any
Welcome to Scala version 2.11.0-20130524-174214-08a368770c (OpenJDK 64-Bit Server VM, Java 1.7.0_21).
Type in expressions to have them evaluated.
Type :help for more information.

scala> "abc".padTo(10, "*").mkString
<console>:7: warning: a type was inferred to be `Any`; this may indicate a programming error.
       val res0 =
           ^
res0: String = abc*******
Run Code Online (Sandbox Code Playgroud)

请注意,这样做是没有错的(本身).

也许有一个用例:

scala> case class Ikon(c: Char) { override def toString = c.toString }
defined class Ikon

scala> List(Ikon('#'),Ikon('@'),Ikon('!')).padTo(10, "*").mkString
res1: String = #@!*******
Run Code Online (Sandbox Code Playgroud)

或更好

scala> case class Result(i: Int) { override def toString = f"$i%03d" }
defined class Result

scala> List(Result(23),Result(666)).padTo(10, "---").mkString
res4: String = 023666------------------------
Run Code Online (Sandbox Code Playgroud)

由于这不是您的用例,也许您应该询问是否要使用冗长且充满危险的API.

这就是丹尼尔的答案是正确答案的原因.我不确定为什么他的示例中的格式字符串看起来如此可怕,但它通常看起来更加温和,因为在大多数可读字符串中,您只需要在几个地方格式化字符.

scala> val a,b,c = "xyz"

scala> f"$a is followed by `$b%10s` and $c%.1s remaining"
res6: String = xyz is followed by `       xyz` and x remaining
Run Code Online (Sandbox Code Playgroud)

您需要添加虚假格式化程序的一种情况是您需要换行符时:

scala> f"$a%s%n$b$c"
res8: String = 
xyz
xyzxyz
Run Code Online (Sandbox Code Playgroud)

我认为插补器应该处理f"$ a%n $ b".哦,坚持,它在2.11修复.

scala> f"$a%n$b"  // old
<console>:10: error: illegal conversion character
              f"$a%n$b"

scala> f"$a%n$b"  // new
res9: String = 
xyz
xyz
Run Code Online (Sandbox Code Playgroud)

所以现在没有理由不插入.