Java字符串填充空格 [英] Java String Padding with spaces

查看:682
本文介绍了Java字符串填充空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 字符串name1 =我的朋友在项目中不得不暗示某些东西,我发现了一些困难, Bharath//长度应该是12 
String name2 =Raju//长度应该是8
String name3 =Rohan//长度应该是9
String name4 = Sujeeth//长度应该是12
String name5 =Rahul//其长度应该是11意味着所有可变长度的字符串

我有字符串和他们的Lengths.I需要得到输出,如下面的格式。通过使用字符串concatination和padding.I需要在Groovy中的答案,即使Java也这是好的..

 Bharath Raju Rohan Sujeeth Rahul

意义:

Bharath向前5个黑色空格,长度为12(7 + 5 = 12),



Raju向前4个黑色空格,长度为8(4 + 4 = 8),

Rohan向前4个黑色空格作为长度是9(5+ 4),

在5个黑色空格中,lenth是12(7 + 5),

Rahul以上6个黑色空格的长度为11(5 + 6),

您可以这样做:

  //名单列表
def names = [Bharath,Raju,Rohan,Sujeeth,Rahul ]

//列宽度列表:
def widths = [12,8,9,12,11]

字符串输出= [名称,宽度] .transpose()。collect {name,width - >
name.padRight(width)
} .join()

输出等于:

 'Bharath Raju Rohan Sujeeth Rahul'

假设我理解了这个问题......很难确定......


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...

这篇关于Java字符串填充空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆