Java String Padding with spaces [duplicate]

匿名 (未验证) 提交于 2019-12-03 01:20:02

问题:

This question already has an answer here:

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

回答1:

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



回答2:

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



回答3:

You can use sprintf, which is added to the Object class so it is always available:

def s = sprintf("%-12s %-8s %-9s %-12s %-11s", name1, name2, name3, name4, name5)  assert s == "Bharath      Raju     Rohan     Sujeeth      Rahul      " 

The formatting string used with sprintf is the same as the format string used for the Formatter class. See the JDK documentation for the format string for more information.



回答4:

As already said, you can use String.format() method to achieve your goal.

For example :

    String[] strings = {             "toto1",             "toto22",             "toto333",             "toto",             "totoaa",             "totobbb",             "totocccc",     };     String marker = "01234567890|";     String output = "";     for(String s : strings) {         output += marker;     }     System.out.println(output);     output = "";     for(String s : strings) {         output += String.format("%-12s", s);     }     System.out.println(output); 

This will output a first line with markers for 12 chars then 2nd line with expected string :

01234567890|01234567890|01234567890|01234567890|01234567890|01234567890|01234567890| toto1       toto22      toto333     toto        totoaa      totobbb     totocccc     


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!