Java 字符串格式(列)
问题描述:
Java 中是否有本机代码或库用于格式化字符串,如下面在 C# 中制作的那样?
Is there a native code or library in Java for formatting a String like in the way below made in C#?
来源:将字符串格式化为列 (C#)
public string DropDownDisplay {
get {
return String.Format("{0,-10} - {1,-10}, {2, 10} - {3,5}"),
Name, City, State, ID);
}
}
答
Java 也有一个 String
格式选项:
Java also have a String
formatting option :
public String DropDownDisplay(){
return String.format("%-10s - %-10s, %10s - %5s", "name", "city", "state", "id");
}
有许多格式说明符:
-
%s
- 字符串值 -
%d
- 十进制整数
-
%s
- String value -
%d
- Decimal integer
要指定宽度,您可以使用 %SomeNumber
选项,
正数将在指定宽度内右对齐,负数将左对齐.
这是您可以使用的 Java 格式示例
For specifying a width you can use the %SomeNumber
option,
positive number will Right-justify within the specified width, and a negative number will be Left-Justify.
Here is Java format examples that you can use