英文:
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<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());
}
答案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<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)) // use "%-5s" to add spaces to the left, "%5s" - to the right
.forEach(f -> System.out.printf("[%s]%n", 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<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");
}
}
Test
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);
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()
和格式字符串"%-99s"
,其中99
是最大字符串长度:
int maxLen = names.stream().mapToInt(String::length).max().orElse(0);
String format = "%-" + maxLen + "s";
names = names.stream()
.map(s -> String.format(format, s))
.collect(Collectors.toList());
终端操作当然应该是你需要的,无论是构建新列表(就像这里演示的一样),打印它们,连接它们,...
英文:
You can use String.format()
with a format string of "%-99s"
, where 99
is the max string length:
int maxLen = names.stream().mapToInt(String::length).max().orElse(0);
String format = "%-" + maxLen + "s";
names = names.stream()
.map(s -> 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 -> String.format("%-" + max.length() + "s", 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("%1$"+length+ "s", string);
Just pass the max length and all your strings to the above method.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论