String Operations

From mi-linux
Jump to navigationJump to search

...Back to 5CS004

Really, really, long strings

Instead of using " you can use """ (three double quote marks) as a string delimeter if you want to define a really, really long string that is split over several lines. Like this:

val really_long_string = """<html>
    <title>Looooong Scala String</title>
    <h1>This is a very long string indeed!</h1>

Splitting strings

Splitting a string means turning it into an array. For example, you might want to take a string like this "Hello world" and turn it into an array of Strings, like this ["Hello", "world"].

Here are more examples:

scala> val mystring = "Hello, I like Scala! It, does, rock."
mystring: java.lang.String = Hello, I like Scala! It, does, rock.

scala> mystring.split(",")
res0: Array[java.lang.String] = Array(Hello,  I like Scala! It,  does,  rock.)

scala> mystring.split(",").foreach((msg:String) => println(msg))
 I like Scala! It


How to remove characters from a string

To remove one or more characters from the start of a String, use the drop() method:

scala> mystring.drop(1)
res6: String = ello world!

scala> mystring.drop(5)
res7: String =  world!


...Back to 5CS004