gpt4 book ai didi

Java String.format 向整数添加空格

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:32:37 27 4
gpt4 key购买 nike

我有一小段代码我不理解输出。

此输出为我的字符串格式文本添加了空格。我做错了什么?

public class HelloWorld{

public static void main(String []args){
int a1 = 540;
int a2 = 492;
int a3 = 200;
int a4 = 500;
int a5 = 600;
String a = "/share.html?title=%1s&description=%2s&image=%3s&width=%4s&height=%5s";
String b = String.format(a, a1, a2, a3, a4, a5);
System.out.println(b);
}
}

输出是:

/share.html?title=540&description=492&image=200&width= 500&height=  600

为什么最后一个宽高上有那些空格?

最佳答案

从格式说明符中删除数字:

String a = "/share.html?title=%s&description=%s&image=%s&width=%s&height=%s";

像您一样在格式说明符中使用数值,您指定了输出的最小宽度 - 这就是您看不到前三个值有任何空格的原因。

如果你想引用一个特定的参数而不是让格式化程序按照指定的顺序计算它们,你可以指定一个参数索引,格式为 n$,其中 n 是参数的索引引用的参数(如 1$2$、...)。

另见 java.util.Formatter获取更多信息。

除了 %s,您还可以指定 %d,因为您所有的参数都是 int 类型。

关于Java String.format 向整数添加空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37791455/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com