Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate padded strings

Tags:

string

scala

I have three strings, for example "A", "B", "C". I have to produce the string which results from concatenating them, only the second string must be padded with whitespace to a given length.

This was my first attempt as guided by intuition and general Scala newbiness:

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

val s = s1 + s2.padTo(padLength, " ") + s3

which is wrong because padTo returns a SeqLike whose toString does not return the string inside but a Vector-like representation.

What would be the best idiomatic way to do this in Scala?

like image 517
Alvaro Rodriguez Avatar asked Jun 07 '13 14:06

Alvaro Rodriguez


2 Answers

String can be (via an implicit conversion to StringOps here) considered like a collection of characters, so your padding should be:

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

Calling .padTo(padLength, " ") on a String actually returns a Seq[Any] since you end up with both chars and strings in your sequence.

like image 171
gourlaysama Avatar answered Oct 31 '22 09:10

gourlaysama


You didn't say whether you want to pad to the left or right. Just use format:

val s = f"$s1%s$s2%20s$s3"

Or, before Scala 2.10 (or if you need "20" as a parameter):

val s = "%s%"+padLength+"s%s" format (s1, s2, s3)

Use negative padding to add padding space to the right instead of the left.

like image 41
Daniel C. Sobral Avatar answered Oct 31 '22 09:10

Daniel C. Sobral