Difference between revisions of "String Operations"

From mi-linux
Jump to navigationJump to search
(Added drop())
m
 
Line 1: Line 1:
 +
...Back to [[5CS004]]
 +
 +
 
== Really, really, long strings ==
 
== Really, really, long strings ==
  
Line 53: Line 56:
 
scala>  
 
scala>  
 
   </nowiki>
 
   </nowiki>
 +
 +
 +
...Back to [[5CS004]]

Latest revision as of 16:05, 7 March 2011

...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>
  <head>
    <title>Looooong Scala String</title>
  </head>
  <body>
    <h1>This is a very long string indeed!</h1>
  </body>
</html>"""
println(really_long_string)
  

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))
Hello
 I like Scala! It
 does
 rock.

scala> 
  


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!

scala> 
  


...Back to 5CS004