.NET String.Format方法是否允许将字符串放置在固定长度字符串中的固定位置.
" String Goes Here" " String Goes Here " "String Goes Here "
这是如何使用.NET完成的?
编辑 - 我尝试过Format/PadLeft/PadRight致死.它们不起作用.我不知道为什么.我最终编写了自己的函数来完成这项工作.
编辑 - 我犯了一个错误,并在格式说明符中使用了冒号而不是逗号.应该是"{0,20}".
感谢所有优秀和正确的答案.
public class Divers {
public static void main(String args[]){
String format = "|%1$-10s|%2$-10s|%3$-20s|\n";
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));
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
|FirstName |Init. |LastName |
|Real | |Gagnon |
|John |D |Doe |
|John |F. |Kennedy |
Run Code Online (Sandbox Code Playgroud)
我希望输出居中.如果我不使用' - '标志,则输出将与右侧对齐.
我没有在API中找到中心文本的标志.
该文章有关于格式的一些信息,但没有对中心自圆其说.