Posted By

hansamann on 02/02/07


Tagged

String gstring groovyseries


Versions (?)

Who likes this?

6 people have marked this snippet as a favorite

cpjobling
jsbournival
bootz15
hendersk
mbanfi
adaptives


Groovy Series: String & GString 2/2


 / Published in: Groovy
 

URL: http://hansamann.podspot.de/files/grails_podcast_episode_29.mp3

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

  1. //we can access the contents of strings with an list-like syntax
  2. def fileName = '/home/username/file.txt'
  3. assert fileName[0] == "/"
  4. assert fileName[-4..-1] == '.txt'
  5. // replace .txt with _old.txt
  6. def fileWithSuffix = fileName - '.txt' + '_old.txt'
  7. assert fileWithSuffix == '/home/username/file_old.txt'
  8.  
  9. //center some text for a nice looking report
  10. def title = 'Report Title'
  11. def centeredTitle = title.center(80)
  12. assert centeredTitle == ' Report Title '
  13.  
  14. //add some text with the left-shift operator
  15. def hello = 'Hello'
  16. hello <<= ' ' << 'World' << '!' //using << returns a StringBuffer!
  17. assert hello != 'Hello World!'
  18. assert hello.toString() == 'Hello World!'
  19.  
  20. //multiply strings
  21. def fiveTimes = "times" * 5
  22. assert fiveTimes == 'timestimestimestimestimes'

Report this snippet  

You need to login to post a comment.