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...
Take a look at Apache's StringUtils. It has methods to pad with spaces (either left or right).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With