Groovy exercises – text wrapping

This is my groovy solution for simple text wrapping problem:

  1.  
  2. def input = "The quick brown fox jumps over the lazy dog. "
  3.  
  4. String.metaClass.wrap = {token, length ->
  5. def line = token
  6. def elements = delegate.tokenize().reverse()
  7.  
  8. while(elements.size()){
  9. if ((line + elements.last()).size() < length){
  10. line += ' ' + elements.pop()
  11. }
  12. else {
  13. println line
  14. line = token
  15. }
  16. }
  17.  
  18. if (line != token){
  19. println line
  20. }
  21. }
  22.  
  23. (input * 10).wrap('>', 72)
  24.  

No Comments yet

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress with GimpStyle Theme design by Horacio Bella.
Entries and comments feeds. Valid XHTML and CSS.