Posted By

hansamann on 01/31/07


String gstring groovyseries

Versions (?)

Who likes this?

6 people have marked this snippet as a favorite


Groovy Series: String & GString 1/2

 / Published in: Groovy


This snippet shows the different types of strings in Groovy and plays with them. Listen to the audio to get the best learning experience. Simply right-click on the title above to download the mp3 file of this part of the series.

The Groovy Series is part of the Grails Podcast and can be subscribed to via: The series is produced by Dierk K├Ânig and Sven Haiges, further information about the topic of this episode can be found in the book

Groovy in Action -

  1. //Single quote = normal Java String
  2. def replacement = 'problem'
  3. def string = 'This is a test. No $replacement'
  4. assert string.size() == 31 //$replacement is counted normally
  6. //GString
  7. def gstring = "This is a test. No $replacement"
  8. assert gstring.size() == 26 //now the chars in 'problem' count
  9. assert gstring == 'This is a test. No problem'
  11. //Multiple lines of normal String text
  12. def multiLine = '''Line One
  13. Line Two
  14. Line Three'''
  15. def lines = multiLine.tokenize("\n")
  16. assert lines.size() == 3
  18. //MultiLine GString
  19. def multiGString = """Groovy can master any $replacement
  20. ${replacement + 's'} have to be solved immediately!"""
  21. lines = multiGString.tokenize("\n")
  22. assert lines.size() == 2
  23. assert lines[1] == 'problems have to be solved immediately!'
  25. //slashy String form
  26. def slashyString = /${lines[0]} in no time. Look, no escaping of \ backslashes/
  27. assert slashyString == 'Groovy can master any problem in no time. Look, no escaping of \\ backslashes'

Report this snippet  


RSS Icon Subscribe to comments
Posted By: mktany2k on February 28, 2007

The test on line 27 will fail because the value for lines[0] will be "Groovy can master any $replacement." with the extra DOT in the end of line.

by remove the DOT. The test pass. Hope this help.

Groovy rocks

Posted By: hansamann on March 2, 2007

Thanx for the correction - the dot is removed. The snippet should now work in groovyConsole without changes... Sven

You need to login to post a comment.