如何使列表中的所有字符串具有相同的长度?

huangapple go评论113阅读模式
英文:

How make all strings in list one length?

问题

我有一个姓名列表,我需要对其进行格式化,使所有字符串的长度相同(在需要的位置添加空格)。我使用Java 8,已经获得了列表中最长的字符串,但我不知道如何将其他字符串与该最大字符串进行比较,并在需要时添加空格。\n\n我的代码:

List<String> names = formatNames(abbreviations);
String max = Collections.max(names, Comparator.comparing(String::length));

private String adjustableString(String format, int number) {
    return IntStream.range(0, number).mapToObj(i -> format).collect(Collectors.joining());
}
英文:

I have a list of names and I need to format it to make all strings same length (add spaces where it needs). Im using java 8 and already got the largest string of list, and I have no idea how to compare other strings to that largest and add spaces where it has to.
My code:

List&lt;String&gt; names = formatNames(abbreviations);
    String max = Collections.max(names, Comparator.comparing(String::length));

private String adjustableString(String format, int number) {
    return IntStream.range(0, number).mapToObj(i -&gt; format).collect(Collectors.joining());
}

答案1

得分: 1

你可以找到字符串的最大长度,然后使用 String.format 进行对齐:

List<String> names = Arrays.asList("a", "bbb", "12345");
int maxLen = names.stream().mapToInt(String::length).max().getAsInt();

names.stream()
     .map(s -> String.format("%-" + maxLen + "s", s)) // 使用 "%-5s" 在左侧添加空格,"%5s" - 在右侧添加空格
     .forEach(f -> System.out.printf("[%s]%n", f));

输出:

[a    ]
[bbb  ]
[12345]

更新
当然,可以使用 orElse(0) 来处理空列表的情况,但是还有另一个机会,可以将可选的最大长度的计算与数组内值的替换连接起来,使用 List::replaceAll,类似于 fps 的建议

static List<String> padAllToMaxLength(List<String> list) {
    list.stream()
        .mapToInt(String::length)
        .max()
        .ifPresent(max -> doPad(max, list));
    return list;
}

private static void doPad(int spaceCount, List<String> list) {
    System.out.println("doPad: " + spaceCount + ", " + list);
    if (spaceCount > 0) {
        Map<Integer, String> spaces = new HashMap<>();
        list.replaceAll(s -> s.length() == spaceCount ? s
                : s + spaces.computeIfAbsent(spaceCount - s.length(), (x) -> " ".repeat(x)));
        System.out.println("space cache: " + spaces);
    } else {
        System.out.println("nothing to pad");
    }
}

测试:

String br = "\n====";
System.out.println("empty list: " + padAllToMaxLength(Collections.emptyList()) + br);
System.out.println("empty values: " + padAllToMaxLength(Arrays.asList("", "", "")) + br);
System.out.println("values: " + padAllToMaxLength(Arrays.asList("", "1", "22", "333", "44", "5", "", "777")) + br);

输出:

empty list: []
====
doPad: 0, [, , ]
nothing to pad
empty values: [, , ]
====
doPad: 3, [, 1, 22, 333, 44, 5, , 777]
space cache: {1= , 2=  , 3=   }
values: [   , 1  , 22 , 333, 44 , 5  ,    , 777]
====
英文:

You could find the max length of the strings and then align them using String.format:

List&lt;String&gt; names = Arrays.asList(&quot;a&quot;, &quot;bbb&quot;, &quot;12345&quot;);
int maxLen = names.stream().mapToInt(String::length).max().getAsInt();

names.stream()
     .map(s -&gt; String.format(&quot;%-&quot;+ maxLen+&quot;s&quot;, s)) // use &quot;%-5s&quot; to add spaces to the left, &quot;%5s&quot; - to the right
     .forEach(f -&gt; System.out.printf(&quot;[%s]%n&quot;, f));

Output:

[a    ]
[bbb  ]
[12345]

Update<br/>
Of course, a case of empty list could be handle using orElse(0), but there is another opportunity to chain calculation of optional max length with replacement of values inside the array using List::replaceAll similar to fps' suggestion:

static List&lt;String&gt; padAllToMaxLength(List&lt;String&gt; list) {
    list.stream()
        .mapToInt(String::length)
        .max()
        .ifPresent(max -&gt; doPad(max, list));
    return list;
}

private static void doPad(int spaceCount, List&lt;String&gt; list) {
    System.out.println(&quot;doPad: &quot; + spaceCount + &quot;, &quot; + list);
    if (spaceCount &gt; 0) {
        Map&lt;Integer, String&gt; spaces = new HashMap&lt;&gt;();
        list.replaceAll(s -&gt; s.length() == spaceCount ? s
                : s + spaces.computeIfAbsent(spaceCount - s.length(), (x) -&gt; &quot; &quot;.repeat(x)));
        System.out.println(&quot;space cache: &quot; + spaces);
    } else {
        System.out.println(&quot;nothing to pad&quot;);
    }
}

Test

String br = &quot;\n====&quot;;
System.out.println(&quot;empty list: &quot; + padAllToMaxLength(Collections.emptyList()) + br);
System.out.println(&quot;empty values: &quot; + padAllToMaxLength(Arrays.asList(&quot;&quot;, &quot;&quot;, &quot;&quot;)) + br);
System.out.println(&quot;values: &quot; + padAllToMaxLength(Arrays.asList(&quot;&quot;, &quot;1&quot;, &quot;22&quot;, &quot;333&quot;, &quot;44&quot;, &quot;5&quot;, &quot;&quot;, &quot;777&quot;)) + br);

Output

empty list: []
====
doPad: 0, [, , ]
nothing to pad
empty values: [, , ]
====
doPad: 3, [, 1, 22, 333, 44, 5, , 777]
space cache: {1= , 2=  , 3=   }
values: [   , 1  , 22 , 333, 44 , 5  ,    , 777]
====

答案2

得分: 1

你可以使用String.format()和格式字符串&quot;%-99s&quot;,其中99是最大字符串长度:

int maxLen = names.stream().mapToInt(String::length).max().orElse(0);
String format = &quot;%-&quot; + maxLen + &quot;s&quot;;
names = names.stream()
             .map(s -&gt; String.format(format, s))
             .collect(Collectors.toList());

终端操作当然应该是你需要的,无论是构建新列表(就像这里演示的一样),打印它们,连接它们,...

英文:

You can use String.format() with a format string of &quot;%-99s&quot;, where 99 is the max string length:

int maxLen = names.stream().mapToInt(String::length).max().orElse(0);
String format = &quot;%-&quot; + maxLen + &quot;s&quot;;
names = names.stream()
             .map(s -&gt; String.format(format, s))
             .collect(Collectors.toList());

The terminal operation should of course be what you need, whether building a new list (like shown here), printing them, concatenating them, ...

答案3

得分: 1

其他答案展示了如何使用格式化字符串创建一个新的列表。这里有一种方法可以原地格式化列表中的字符串:

names.replaceAll(s -> String.format("%-" + max.length() + "s", s));

这假设 max 是具有最大长度的列表字符串。它使用了 List.replaceAll,该方法接受一个一元操作符,用于转换列表的所有元素。

英文:

Other answers show how to create a new list with the strings formatted. Here's a way to format the strings of the list, in-place:

names.replaceAll(s -&gt; String.format(&quot;%-&quot; + max.length() + &quot;s&quot;, s));

This assumes that max is the string of the list with max length. It uses List.replaceAll, which accepts a unary operator to transform all the elements of the list.

答案4

得分: -1

你可以使用 String.format 格式化字符串,并在需要的地方添加空格:

String.format("%1$" + length + "s", string);

只需将最大长度和所有字符串传递给上述方法。

英文:

You can format a string and add spaces where it's needed with String.format:

String.format(&quot;%1$&quot;+length+ &quot;s&quot;, string);

Just pass the max length and all your strings to the above method.

huangapple
  • 本文由 发表于 2020年10月28日 00:52:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/64559228.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定