String Processing

Scala strings are Java strings, but instances of the String class are implicitly converted into instances of:

scala.collections.immutable.StringOps

Building

var noun = "the city"
var verb = "is big"                      
var sentence = noun + " " + verb

Parsing

for(i <- 0 until sentence.size) {
   println(sentence(i))
}

for(c <- sentence) {
   println(c)
}

sentence.substring(4, 8)

sentence.split("\\s+")

Taking and Dropping

Scala provides many ways to extract substrings from a string.

Recall that Scala functions can be passed as parameters to other functions.

Scala's takeWhile and dropWhile methods take or drop all characters from the beginning of a string that pass a test which is passed as a function parameter.

To demonstrate, here's a session with Evaluator.scala, which executes expressions of the form:

EXP ::= BLANK*~NUMBER~BLANK*~OPERATOR~BLANK*~NUMBER~BLANK*
NUMBER ::= DIGIT+(~.~DIGIT+)?
BLANK ::= TAB | SPACE | NEWLINE
OPERATOR ::= + | *

("~" means "followed by".)

->    3.01 *4.2
result = 12.642
-> 3+4
result = 7.0
-> x + 4
java.lang.Exception: operands must be numbers
-> 3 # 4
java.lang.Exception: operator must be + or *
-> quit
bye