Home > Software engineering >  Stars and string combination pattern in Scala
Stars and string combination pattern in Scala

Time:10-16

I am very new to scala programming , and I'm stuck with this particular task.

So this is my scala code:

object task {
  def main(args: Array[String]) = {
    val mystring: Array[String] = Array("This\nis\nrandom\ntext\n\n")
    val s = mystring.mkString.split("\n")

    println("**********")
    for(element <- s) 
        {
        println("* "   element    "  *")
        }
    println("**********")
  }
}

and I get something like this:

**********
* This  *
* is  *
* random  *
* text  *
**********

but the main goal is to get this:

**********
* This   *
* is     *
* random *
* text   *
**********

Does anyone know how to solve this?

CodePudding user response:

You need to apply a little math.

val mystring = "This\nis\nrandom\ntext\n\n"
val s = mystring.split("\n")
val mxLen = s.map(_.length).max

println("*" * (mxLen 4))
for(element <- s) {
  val eLen = element.length
  println("* "   element    " "*(mxLen-eLen)   " *")
}
println("*" * (mxLen 4))
  • Related