Splitting Strings

In the following lesson, you will learn how to split strings in Scala.

We'll cover the following

Problem

Imagine you have a list of items separated by a comma. You want to print the list vertically, item-by-item to make it easier to read. In other words, you want the compiler to split the string into separate lines at the commas.

Solution

In Scala, you can use the split method to split strings at specific separators such as commas. split converts a string into an array of String elements and returns that array. For instance, if we have a string "a,b,c" and apply the split method on it, we would get an array of type String containing three elements: "a","b", and "c".

An array is a collection of elements of the same data type. For now, you can think of it as a variable that can store multiple values and each value has its own unique place. We will look at arrays in a later lesson in the course.

Let’s look at the syntax:

split takes one argument which lets the compiler know which separator it should split the string at. In our example, we are splitting at a comma, but you can choose any separator you want; "#", "*", etc.

Press + to interact
val splitPizza = "Pizza Dough,Tomato Sauce,Cheese,Toppings of Choice".split(",")
// Driver Code
splitPizza.foreach(println)

You might have noticed that we haven’t used the conventional syntax for printing; println(VariableName). The reason for this, as discussed above, is that we aren’t just printing a simple variable, rather, we are printing the elements of an array. foreach is a method which is used to perform an operation on every element of a collection of elements. In our case, the operation we want to perform on each element is to print it. If you don’t understand this, that’s okay, the foreach method is discussed in detail in a later lesson. For now, all you need to know is that it is printing every element of the array.


Let’s move on to the next problem, character processing.