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()  


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...