String Manipulation

This is an outline of all of the various String manipulation methods available in Scala. Of course, all methods from java.lang.String are available to you, but often the Scala equivalents make it easier to work inside of Scala by providing List or other Scala-specific results.

TOC

Tokenizing, splitting and joining

There are several methods available that perform the basic job of breaking a String up into parts:

  • scala.List#fromString(x: String) - Takes one string as an argument and makes each character in the String an element in a new List. Example:
    scala> var x = List.fromString("Test")            
    x: scala.List[scala.Char] = List(T,e,s,t)
    
  • scala.List#fromString(x: String, s: Char) - Takes the input string as well as a separator character and breaks the string into list elements on the separator. Example:
    scala> var x = List.fromString("This is a test", ' ')
    x: scala.List[java.lang.String] = List(This,is,a,test)
    
  • scala.runtime.RichString#split(s: Char) - This is the version you would normally get if you issue “split” on a String in Scala that’s not explicitly a java.lang.String. Returns an Array of Strings. Example:
    scala> var x = "This is a test".split(' ')
    x: scala.Array[java.lang.String] = [Ljava.lang.String;@c37f31
    

If you want more complex ways of tokenizing strings, there is a (not well documented) set of classes under scala.util.parsing that is described a little in Scala by Example.

Likewise there are ways of putting a string back together from an Array or List:

  • scala.Iterable.mkString(sep: String, start: String, end: String) - Concatenates all of the parts of the sequence (Lists, Arrays, Sets, etc) with the given separator, adding start at the start of the string and end at the end. Since this method is on the Iterable trait, there are a wide variety of objects it can be used on. In addition, since this is a trait method, the implementation is already provided for you in case you write your own Iterable classes. There is a new version in 2.4.0 and greater that lets you omit start and end. Example:
    scala> var x = List.fromString("This is a test", ' ')
    x: scala.List[java.lang.String] = List(This,is,a,test)
    
    scala> x.mkString("[", ",", "]")  
    line4: java.lang.String = [This,is,a,test]
    
  • You can also use the foldLeft, foldRight, reduceLeft, or reduceRight operators, which could give you more control over how the string is concatenated. For example, you can concatenate in reverse order:
    scala> x
    line11: scala.List[java.lang.String] = List(This,is,a,test)
    
    scala> x.reduceLeft[String]( (y, z) => z + "," + y)
    line12: java.lang.String = test,a,is,This
    
 
common/string-manipulation.txt · Last modified: 2007/03/15 19:57 by dchenbecker
 
Recent changes RSS feed Valid XHTML 1.0 Driven by DokuWiki