Thursday, October 1, 2009

Strings

This topic simply shows several things that can be done with strings. It is not exhaustive and focusses of things that cannot as easily be done with java strings.

Note: Because I am using Scala 2.7 we often need to use mkString to convert the processed string from a sequence of characters to a string. In scala 2.8 this is not required.

  1. /*
  2.    Making use of raw strings to create a multi line string
  3.    I add a | at the beginning of each line so that we can line up the quote nicely 
  4.    in source code then later strip it from the string using stripMargin
  5. */
  6. scala>val quote = """|I don-t consider myself a pessimist.                                                                                                
  7.      |                |I think of a pessimist as someone who is waiting for it to rain.
  8.      |                |And I feel soaked to the skin.
  9.      | 
  10.      |                |Leonard Cohen"""
  11. quote: java.lang.String = 
  12. |I don-t consider myself a pessimist. 
  13.                       |I think of a pessimist as someone who is waiting for it to rain.
  14.                       |And I feel soaked to the skin.
  15.        
  16.                       |Leonard Cohen
  17. // capilize the first character of each line
  18. scala>val capitalized = quote.lines.
  19.      |                         map( _.trim.capitalize).mkString("\n")
  20. capitalized: String = 
  21. |I don-t consider myself a pessimist.
  22. |I think of a pessimist as someone who is waiting for it to rain.
  23. |And I feel soaked to the skin.
  24. |Leonard Cohen
  25. // remove the margin of each line
  26. scala> quote.stripMargin        
  27. res1: String = 
  28. I don-t consider myself a pessimist. 
  29. I think of a pessimist as someone who is waiting for it to rain.
  30. And I feel soaked to the skin.
  31.        
  32. Leonard Cohen
  33. // this is silly.  I reverse the order of each word but keep the words in order
  34. scala> quote.stripMargin.         
  35.      |       lines.               
  36.      |       map( _.split(" ").   
  37.      |              map(_.reverse).
  38.      |              mkString (" ")).
  39.      |      mkString("\n")
  40. res16: String = 
  41. I t-nod redisnoc flesym a .tsimissep
  42. I kniht fo a tsimissep sa enoemos ohw si gnitiaw rof ti ot .niar
  43. dnA I leef dekaos ot eht .niks
  44. dranoeL nehoC
  45. scala>val myPatch = "-->This is my patch<--"                
  46. myPatch: java.lang.String = -->This is my patch<--
  47. // I replace the characters from point 10 in the string to myPatch.length 
  48. // (the full patch string)
  49. scala> quote.patch(10, myPatch, myPatch.length).mkString     
  50. res21: String = 
  51. |I don-t c-->This is my patch<--mist.
  52.                       |I think of a pessimist as someone who is waiting for it to rain.
  53.                       |And I feel soaked to the skin.
  54.        
  55.                       |Leonard Cohen
  56. // drop the first 3 lines of the string.  
  57. // there is also a take method
  58. scala> quote.lines.drop(3).mkString("\n").stripMargin 
  59. res25: String = 
  60.        
  61. Leonard Cohen
  62. // a bunch of examples of converting strings
  63. scala>"1024".toInt
  64. res26: Int = 1024
  65. scala>"1024".toFloat
  66. res27: Float = 1024.0
  67. scala>"1024".toDouble
  68. res28: Double = 1024.0
  69. scala>"1024".toLong  
  70. res29: Long = 1024
  71. scala>"102".toByte 
  72. res31: Byte = 102
  73. scala>"true".toBoolean
  74. res32: Boolean = true
  75. // format uses the java.util.Formatter class to format a string
  76. scala>"Hello %s,\nThe date is %2$tm %2$te,%2$tY".format("Jesse", new java.util.Date()) 
  77. res35: String = 
  78. Hello Jesse,
  79. The date is 09 30,2009
  80. /*
  81.    More silliness
  82.    I am replacing every other character with the character of the reversed string
  83.   
  84.    this is done by 
  85.    1. convert string to a list and zip it together with its reverse
  86.       We may still need to cover zipping.  It basically matches up the 
  87.       corresponding elements of two lists into one list
  88.       so 1,2,3 and one,two,three zipped would be (1,one),(2,two),(3,three)
  89.    2. Add an index to each element in the list with zipWithIndex
  90.    3. Use map to check if the element is an odd element using the index and return either the original element or the reversed element
  91.   
  92.    Not useful but interesting use of functional idioms
  93. */
  94. scala> quote.toList.                                          
  95.      |       zip(quote.reverse.toList).                       
  96.      |       zipWithIndex.                                    
  97.      |       map {                                            
  98.      |            case ((original,reversed),index) if(index % 2 == 0) => original
  99.      |            case ((original,reversed),index) => reversed                   
  100.      |           }.                                                              
  101.      |       mkString                                                            
  102. res42: String = |e oo -r noes|d r m s l     e s m s .        . i s e t o   e|a shlne  f anp|s i i t a   o e n   h  .siwrioi gifrrfig ioirwis.  h   n e o   a t i i s|pna f  enlhs a|e   o t e s i .        . s m s e     l s m r d|seon r- oo e|
  103. // filter out all non-vowels
  104. scala> quote.filter( "aeiou" contains _ ).mkString
  105. res51: String = ooieeaeiiioaeiiaoeoeoiaiioioaieeoaeoeieoaoe

1 comment:

  1. Note that mkString is rather inefficient.
    It cannot preallocate the buffer, because it's a very generic implementation.
    See the recent discussion on the Scala mailing list

    ReplyDelete