本文介紹了如何使用 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.
推薦答案
我很快就解決了這個問題.您現(xiàn)在可以在 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 使字符串居中?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權益,請聯(lián)系我們刪除處理,感謝您的支持!