程式扎記: [ GroovyGN ] Padding Strings

標籤

2015年7月27日 星期一

[ GroovyGN ] Padding Strings

Source From Here
Preface
Groovy extends the String class with a couple of padding methods. These methods allows us to define a fixed width a String value must occupy. If the Stringitself is less than the fixed width then the space is padded with spaces or any other character or String we define. We can pad to the left or the right of the Stringor both left and right and put the String in the center.

Sample Code
These methods are especially useful when we create Groovy scripts that run on the console and we want to format some output.
  1. assert '   Groovy   ' == 'Groovy'.center(12)  
  2. assert 'Groovy      ' == "Groovy".padRight(12)  
  3. assert '      Groovy' == /Groovy/.padLeft(12)  
  4.   
  5. assert '---Groovy---' == "Groovy".center(12'-')  
  6. assert 'Groovy * * *' == "Groovy".padRight(12' *')  
  7. assert 'Groovy Groovy Groovy' == 'Groovy'.padLeft(20'Groovy ')  
  8.   
  9. def createOutput = {  
  10.     def table = [  
  11.         // Page,    Response time, Size  
  12.         ['page1.html',        2001201],  
  13.         ['page2.html',         428853],  
  14.         ['page3.html',         983432],  
  15.         ['page4.html',        4329081]  
  16.     ]  
  17.   
  18.     def total = { data, index ->  
  19.         data.inject(0) { result, row -> result += row[index] }  
  20.     }  
  21.     def totalTime = total.curry(table, 1)  
  22.     def totalSize = total.curry(table, 2)  
  23.   
  24.     def out = new StringBuffer()  
  25.     out << ' Summary '.center(15"*") << '\n\n'  
  26.     out << 'Total pages:'.padRight(25)  
  27.     out << table.size().toString().padLeft(6) << '\n'  
  28.     out << 'Total response time (ms):'.padRight(25)  
  29.     out << totalTime().toString().padLeft(6) << '\n'  
  30.     out << 'Total size (KB):'.padRight(25)  
  31.     out << totalSize().toString().padLeft(6) << '\n\n'  
  32.   
  33.     out << ' Details '.center(15"*") << '\n\n'  
  34.     table.each {  
  35.         out << it[0].padRight(14)  
  36.         out << it[1].toString().padLeft(5)  
  37.         out << it[2].toString().padLeft(8)  
  38.         out << '\n'  
  39.     }  
  40.     out.toString()  
  41. }  
  42.   
  43. assert '''\  
  44. *** Summary ***  
  45.   
  46. Total pages:                  4  
  47. Total response time (ms):   772  
  48. Total size (KB):          22567  
  49.            
  50. *** Details ***  
  51.   
  52. page1.html      200    1201  
  53. page2.html       42    8853  
  54. page3.html       98    3432  
  55. page4.html      432    9081  
  56. ''' == createOutput()  


沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!