Bha*_*A N 4 java string groovy
朋友我必须在项目中捏造一些东西,我发现了一些困难,如下:
String name1 = "Bharath" // its length should be 12
String name2 = "Raju" // its length should be 8
String name3 = "Rohan" // its length should be 9
String name4 = "Sujeeth" // its length should be 12
String name5 = "Rahul" // its length should be 11 " Means all Strings with Variable length"
Run Code Online (Sandbox Code Playgroud)
我有字符串和它们的长度.我需要输出如下格式.通过使用字符串连接和填充.我需要在Groovy中回答,即使Java也很好..
"Bharath Raju Rohan Sujeeth Rahul "
Run Code Online (Sandbox Code Playgroud)
手段:
Bharath以5个黑色空格作为lenth是12(7 + 5 = 12),
Raju从4个黑色空间开始,因为lenth是8(4 + 4 = 8),
Rohan向前开了4个黑色空格,因为lenth是9(5 + 4),
Sujeeth向前5个黑色空间,因为lenth是12(7 + 5),
Rahul开出6个黑色空间,因为lenth是11(5 + 6),
你可以这样做:
// A list of names
def names = [ "Bharath", "Raju", "Rohan", "Sujeeth", "Rahul" ]
// A list of column widths:
def widths = [ 12, 8, 9, 12, 11 ]
String output = [names,widths].transpose().collect { name, width ->
name.padRight( width )
}.join()
Run Code Online (Sandbox Code Playgroud)
这output
相当于:
'Bharath Raju Rohan Sujeeth Rahul '
Run Code Online (Sandbox Code Playgroud)
假设我理解这个问题......很难确定......
归档时间: |
|
查看次数: |
13970 次 |
最近记录: |