1.5. Processing a String One Character at a Time
Problem
You want to iterate through each character in a string, performing an operation on each character as you traverse the string.
Solution
Depending on your needs and preferences, you can use the map or foreach methods, a for loop, or other approaches. Here’s a simple
example of how to create an uppercase string from an input string, using
map:
scala> val upper = "hello, world".map(c => c.toUpper)
upper: String = HELLO, WORLDAs you’ll see in many examples throughout this book, you can shorten that code using the magic of Scala’s underscore character:
scala> val upper = "hello, world".map(_.toUpper)
upper: String = HELLO, WORLDWith any collection—such as a sequence of characters in a
string—you can also chain collection methods together to achieve a
desired result. In the following example, the filter method is called on the original
String to create a new String with all occurrences of the lowercase
letter “L” removed. That String is
then used as input to the map method
to convert the remaining characters to uppercase:
scala> val upper = "hello, world".filter(_ != 'l').map(_.toUpper)
upper: String = HEO, WORDWhen you first start with Scala, you may not be comfortable with
the map method, in which case you can
use Scala’s for loop to achieve the
same result. This example shows another way to print each
character:
scala> for (c <- "hello") println(c)
h
e
l
l
oTo write a for loop to work
like a map method, add a yield statement to the end ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access