How to center a string using String.format?(如何使用 String.format 使字符串居中?)
问题描述
public class Divers {
public static void main(String args[]){
String format = "|%1$-10s|%2$-10s|%3$-20s|
";
System.out.format(format, "FirstName", "Init.", "LastName");
System.out.format(format, "Real", "", "Gagnon");
System.out.format(format, "John", "D", "Doe");
String ex[] = { "John", "F.", "Kennedy" };
System.out.format(String.format(format, (Object[])ex));
}
}
输出:
|FirstName |Init. |LastName |
|Real | |Gagnon |
|John |D |Doe |
|John |F. |Kennedy |
我希望输出居中.如果我不使用 '-' 标志,输出将向右对齐.
I want the output to be centered. If I do not use '-' flag the output will be aligned to the right.
我没有在 API 中找到使文本居中的标志.
I did not find a flag to center text in the API.
这篇文章有一些关于格式的信息,但没有关于中心对齐的信息.
This article has some information about format, but nothing on centre justify.
推荐答案
我很快就解决了这个问题.您现在可以在 String.format
中使用 StringUtils.center(String s, int size)
.
I quickly hacked this up. You can now use StringUtils.center(String s, int size)
in String.format
.
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;
import org.junit.Test;
public class TestCenter {
@Test
public void centersString() {
assertThat(StringUtils.center(null, 0), equalTo(null));
assertThat(StringUtils.center("foo", 3), is("foo"));
assertThat(StringUtils.center("foo", -1), is("foo"));
assertThat(StringUtils.center("moon", 10), is(" moon "));
assertThat(StringUtils.center("phone", 14, '*'), is("****phone*****"));
assertThat(StringUtils.center("India", 6, '-'), is("India-"));
assertThat(StringUtils.center("Eclipse IDE", 21, '*'), is("*****Eclipse IDE*****"));
}
@Test
public void worksWithFormat() {
String format = "|%1$-10s|%2$-10s|%3$-20s|
";
assertThat(String.format(format, StringUtils.center("FirstName", 10), StringUtils.center("Init.", 10), StringUtils.center("LastName", 20)),
is("|FirstName | Init. | LastName |
"));
}
}
class StringUtils {
public static String center(String s, int size) {
return center(s, size, ' ');
}
public static String center(String s, int size, char pad) {
if (s == null || size <= s.length())
return s;
StringBuilder sb = new StringBuilder(size);
for (int i = 0; i < (size - s.length()) / 2; i++) {
sb.append(pad);
}
sb.append(s);
while (sb.length() < size) {
sb.append(pad);
}
return sb.toString();
}
}
这篇关于如何使用 String.format 使字符串居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 String.format 使字符串居中?
基础教程推荐
- 降序排序:Java Map 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01