如何格式化将常量变量传递为长度宽度的字符串?
How to format a string passing a constant variable as length width?
我正在学习 Java 所以也许这是一个愚蠢的问题,但它就是。我知道可以使用 .format
方法在 java 中格式化 String
变量:
String.format("|%20s|", "Hello world");
>>| Hello world|
但是如何使用变量指定宽度?即,而不是输入乱七八糟的“20”:
String.format("|%MY_VARs|", "Hello world"); //<-- how to put MY_VAR inside?
String format = String.format("|%%%d|", YOUR_VAR);
String formatted = String.format(format, "hello world");
尝试使用以下 String.format("|%" + MY_VARs +"s|", "Hello world");
格式示例:
int age = 19;
String name = "Dinh";
System.out.println(String.format("My name is %s and I am %s years old", name, age));
应该打印 > 'My name is Dinh and I am 19 years old'
String formatted = String.format(String.format("|%%d|", YOUR_VAR), "hello world");
您还可以查看其中一篇文章:
https://dzone.com/articles/javaone-2017-day-1-keynote-notes-and-thoughts
我正在学习 Java 所以也许这是一个愚蠢的问题,但它就是。我知道可以使用 .format
方法在 java 中格式化 String
变量:
String.format("|%20s|", "Hello world");
>>| Hello world|
但是如何使用变量指定宽度?即,而不是输入乱七八糟的“20”:
String.format("|%MY_VARs|", "Hello world"); //<-- how to put MY_VAR inside?
String format = String.format("|%%%d|", YOUR_VAR);
String formatted = String.format(format, "hello world");
尝试使用以下 String.format("|%" + MY_VARs +"s|", "Hello world");
格式示例:
int age = 19;
String name = "Dinh";
System.out.println(String.format("My name is %s and I am %s years old", name, age));
应该打印 > 'My name is Dinh and I am 19 years old'
String formatted = String.format(String.format("|%%d|", YOUR_VAR), "hello world");
您还可以查看其中一篇文章:
https://dzone.com/articles/javaone-2017-day-1-keynote-notes-and-thoughts