This snippet gives you some interesting examples what you can do with Strings and GStrings in Groovy. 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: http://hansamann.podspot.de/rss. 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 - http://groovy.canoo.com/gina
- //we can access the contents of strings with an list-like syntax
- def fileName = '/home/username/file.txt'
- assert fileName == "/"
- assert fileName[-4..-1] == '.txt'
- // replace .txt with _old.txt
- def fileWithSuffix = fileName - '.txt' + '_old.txt'
- assert fileWithSuffix == '/home/username/file_old.txt'
- //center some text for a nice looking report
- def title = 'Report Title'
- assert centeredTitle == ' Report Title '
- //add some text with the left-shift operator
- def hello = 'Hello'
- hello <<= ' ' << 'World' << '!' //using << returns a StringBuffer!
- assert hello != 'Hello World!'
- assert hello.toString() == 'Hello World!'
- //multiply strings
- def fiveTimes = "times" * 5
- assert fiveTimes == 'timestimestimestimestimes'
You need to login to post a comment.