Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String Padding with spaces [duplicate]

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

like image 696
Bharath A N Avatar asked Dec 05 '22 15:12

Bharath A N


2 Answers

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

like image 198
tim_yates Avatar answered Dec 15 '22 08:12

tim_yates


Take a look at Apache's StringUtils. It has methods to pad with spaces (either left or right).

like image 23
npinti Avatar answered Dec 15 '22 09:12

npinti