java中的字符串格式,最大宽度和结束括号位于单词末尾
我想得到下面的格式java中的字符串格式,最大宽度和结束括号位于单词末尾,java,string,format,Java,String,Format,我想得到下面的格式 abc 12 [hello-wo] this is message1 abc 12 [hello-world] this is message2 abc 10 [hello-wor] this is message2 我试着用 String format1 = "%s %d [%s-%s] %s\n"; String format2 = "%s %d [%s-%-20s] %s\n"; String a = String.format
abc 12 [hello-wo] this is message1
abc 12 [hello-world] this is message2
abc 10 [hello-wor] this is message2
我试着用
String format1 = "%s %d [%s-%s] %s\n";
String format2 = "%s %d [%s-%-20s] %s\n";
String a = String.format(format1,"abc","12",hello,"wo","this is message1");
System.out.print(a);
我使用两种格式format1和format2得出如下结果
格式1
格式2
我想要的是将参数的最后一部分对齐在相同的垂直位置,并且结束方括号应该位于第四个参数的末尾,没有任何空格。您描述的是转换参数。这不是格式化程序通常要做的,除非使用数字和日期,即非常具体的东西 我认为,您无法随心所欲,但您可以通过使用模式和手动转换arg来解决此问题,如下所示: 模式:
String PATTERN = "%s %d [%s-%-21s %s\n"; // notice that I've removed the closing bracket.
// See below
应用参数:
String arg = "world";
arg = arg.trim();
arg = arg.substring(0, Math.min(arg.length(), 20));
String.format(PATTERN, "abc", "12", "hello",
/*Attention here: changing next argument by appending close bracket */
arg + "]",
"this is the message");
你所描述的是改变论点。这不是格式化程序通常要做的,除非使用数字和日期,即非常具体的东西 我认为,您无法随心所欲,但您可以通过使用模式和手动转换arg来解决此问题,如下所示: 模式:
String PATTERN = "%s %d [%s-%-21s %s\n"; // notice that I've removed the closing bracket.
// See below
应用参数:
String arg = "world";
arg = arg.trim();
arg = arg.substring(0, Math.min(arg.length(), 20));
String.format(PATTERN, "abc", "12", "hello",
/*Attention here: changing next argument by appending close bracket */
arg + "]",
"this is the message");
以下是解决问题的技巧:
public void formatString(String hello) {
String format1 = "%s %s %s\n";
String firstPart = String.format("%s %d [%s-%s]", "abc", 12, hello, "wo");
String a = String.format(
format1, firstPart,
String.format("%0" + Math.abs(30 - firstPart.length()) + "d", 0).replace("0", " "),
"this is message1");
System.out.print(a);
}
测试用例:
formatString("hello-wda");
formatString("hello-world");
formatString("hello-wor");
输出
abc 12 [hello-wda-wo] this is message1
abc 12 [hello-world-wo] this is message1
abc 12 [hello-wor-wo] this is message1
诀窍是使用两种格式,第一种是创建第一部分,我们需要这部分来计算需要平衡的空间数量,第二种格式是组合第一部分+第一部分和第二部分之间的空间+第二部分
我使用30作为默认值,您可以根据需要更改它。以下是解决问题的技巧:
public void formatString(String hello) {
String format1 = "%s %s %s\n";
String firstPart = String.format("%s %d [%s-%s]", "abc", 12, hello, "wo");
String a = String.format(
format1, firstPart,
String.format("%0" + Math.abs(30 - firstPart.length()) + "d", 0).replace("0", " "),
"this is message1");
System.out.print(a);
}
测试用例:
formatString("hello-wda");
formatString("hello-world");
formatString("hello-wor");
输出
abc 12 [hello-wda-wo] this is message1
abc 12 [hello-world-wo] this is message1
abc 12 [hello-wor-wo] this is message1
诀窍是使用两种格式,第一种是创建第一部分,我们需要这部分来计算需要平衡的空间数量,第二种格式是组合第一部分+第一部分和第二部分之间的空间+第二部分
我使用30作为默认值,您可以根据需要更改它。因此,基本上,您需要一个输出,例如[hello-world];尽管世界单词很长,但它仍在右括号旁边?因此,基本上,您需要一个输出,例如[hello-world];尽管世界字很长,但它在结束括号旁边?