1.9. Accessing a Character in a String
Problem
You want to get a character at a specific position in a string.
Solution
You could use the Java charAt method:
scala> "hello".charAt(0)
res0: Char = hHowever, the preferred approach is to use Scala’s Array notation:
scala>"hello"(0)res1: Char = h scala>"hello"(1)res2: Char = e
Discussion
When looping over the characters in a string, you’ll normally use
the map or foreach methods, but if for some reason those
approaches won’t work for your situation, you can treat a String as an Array, and access each character with the
array notation shown.
The Scala array notation is different than Java because in Scala it’s really a method call, with some nice syntactic sugar added. You write your code like this, which is convenient and easy to read:
scala> "hello"(1)
res0: Char = eBut behind the scenes, Scala converts your code into this:
scala> "hello".apply(1)
res1: Char = eThis little bit of syntactic sugar is explained in detail in Recipe 6.8.
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