Lesson Overview

Welcome! In this lesson, we'll explore Scala's string manipulation capabilities, focusing on methods like split, mkString, trim, and how to perform type conversions. Scala's powerful string methods simplify text processing, enhancing the readability and efficiency of our code.

Understanding Scala's `split` Function

Working with strings often requires breaking them into smaller sections or 'tokens'. In Scala, the split method achieves this by dividing a string into an array of substrings using a specified delimiter. If no delimiter is provided, you can split by whitespace using regular expressions.

object Solution {
  def main(args: Array[String]): Unit = {
    val sentence = "Scala is fun!"
    val words = sentence.split(" ") // splitting by whitespace
    println(words.mkString("[", ", ", "]")) // Output: [Scala, is, fun!]
  }
}

In the example above, we see that split divides the sentence into words. You can opt for different delimiters, such as a comma.

object Solution {
  def main(args: Array[String]): Unit = {
    val data = "John,Doe,35,Engineer"
    val info = data.split(",") // provided a ',' delimiter
    println(info.mkString("[", ", ", "]"))  // Output: [John, Doe, 35, Engineer]
  }
}
Exploring the `mkString` Method

Conversely, Scala's mkString method concatenates, or 'joins', elements of a collection into a single string:

object Solution {
  def main(args: Array[String]): Unit = {
    val words = Array("Programming", "with", "Scala", "is", "exciting!")
    val sentence = words.mkString(" ")
    println(sentence)  // Output: Programming with Scala is exciting!
  }
}

Here, mkString takes an array of words and merges them into a single sentence using a space as a delimiter.

Mastering the `trim` Method

Detecting and handling extra spaces in strings is crucial, as they may lead to issues. Scala's trim method removes leading and trailing spaces, tabs, or newline characters from a string:

object Solution {
  def main(args: Array[String]): Unit = {
    var name = "    John Doe    \t\n"
    name = name.trim
    println(name)  // Output: John Doe
  }
}

Similarly, use stripMargin for removing whitespace from structured text strings, such as multiline strings with margins.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal