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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With