Java字符串填充空格

4

朋友们,我需要在项目中实现一些东西,但遇到了一些困难,具体如下:

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"

我有字符串和它们的长度。我需要按照以下格式输出结果。通过使用字符串连接和填充。我需要在Groovy中得到答案,即使是Java也可以。
"Bharath     Raju    Rohan    Sujeeth     Rahul     "

意思:

巴拉特以后有5个黑色空格,长度为12(7 + 5 = 12)。

拉朱以后有4个黑色空格,长度为8(4 + 4 = 8)。

罗汉以后有4个黑色空格,长度为9(5 + 4)。

苏杰以后有5个黑色空格,长度为12(7 + 5)。

拉胡尔以后有6个黑色空格,长度为11(5 + 6)。


问题中无法看到空格。我已经在问题中解释了。请有人帮助我。 - Bharath A N
尝试使用java.util.FormatterString.format()来实现这个。 - RP-
4个回答

8
你可以这样做:
// 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()

这会使output等于:
'Bharath     Raju    Rohan    Sujeeth     Rahul      '

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

3
您可以使用sprintf,它已添加到Object类中,因此始终可用:
def s = sprintf("%-12s %-8s %-9s %-12s %-11s", name1, name2, name3, name4, name5)

assert s == "Bharath      Raju     Rohan     Sujeeth      Rahul      "

使用 sprintf 的格式化字符串与 Formatter 类使用的格式化字符串相同。有关更多信息,请参见JDK文档中的格式化字符串部分

3
请看Apache的StringUtils,里面有添加空格(左对齐或右对齐)的方法。

3
如果你使用Groovy,就不需要另外的依赖了……它已经有padLeftpadRight作为String的metaClass方法 - tim_yates
1
@tim_yates:我通常发现Util类非常方便,我会推荐使用它们。话虽如此,如果只是为了这个操作,我同意你避免额外的依赖。 - npinti

2
如前所述,您可以使用String.format()方法来实现您的目标。
例如:
    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);

这将输出一个带有12个字符标记的第一行,然后是带有期望字符串的第二行:
01234567890|01234567890|01234567890|01234567890|01234567890|01234567890|01234567890|
toto1       toto22      toto333     toto        totoaa      totobbb     totocccc    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接