java中数不够用空格填充,Java字符串填充空格

Friends I have to impliment something in project, I found some difficulties, and is as follows:

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"

I have the Strings and their Lengths.I need to get output as in the below format.By using string concatination and padding.I need answer in Groovy, Even if Java also it is fine..

"Bharath Raju Rohan Sujeeth Rahul "

Means:

Bharath onwards 5 black spaces as lenth is 12 (7+5 = 12),

Raju onwards 4 black spaces as lenth is 8 (4+4 = 8),

Rohan onwards 4 black spaces as lenth is 9(5+4),

Sujeeth onwards 5 black spaces as lenth is 12 (7+5),

Rahul onwards 6 black spaces as lenth is 11(5+6),

解决方案

You could do this:

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

Which makes output equal to:

'Bharath Raju Rohan Sujeeth Rahul '

Assuming I understand the question... It's quite hard to be sure...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值