我能用String.format()和String数组参数一起使用吗?

huangapple go评论60阅读模式
英文:

Can I use String.format() with String array parameter?

问题

可以根据可变数量的参数来格式化字符串吗?

例如,如果我有一个字符串数组 arg,其中可以是任意数量的参数,是否可能获得一个格式化的字符串(假设消息字符串中的 %s 的数量与 arg 数组的长度相同?)

private static String getValue(String... arg) {
  String value = String.format(message, arg);
}

谢谢。

英文:

Is it possible to format a string given a variable number of arguments?

For example, if I have String array arg which can be any number of arguments, is it possible to get a formatted string (assuming the message string has the same number of %s as the length of the arg array?)

private static String getValue(String... arg) {
  String value = String.format(message, arg);
}

Thank you.

答案1

得分: 1

一般是这样的:

String[] d = {"abc", "123", "ddd"};
System.out.printf("%s - %s: %s%n", d);

输出:

abc - 123: ddd

然而,如果您需要使用相同分隔符获取单个字符串,最好使用静态方法 String.join

System.out.println(String.join(": ", d)); // 输出 abc: 123: ddd
英文:

Generally yes:

String[] d = {"abc", "123", "ddd"};
System.out.printf("%s - %s: %s%n", d);

prints:

abc - 123: ddd

However, it may be better to use static method String.join if you need to get a single string with the same separator:

System.out.println(String.join(": ", d)); // prints abc: 123: ddd

huangapple
  • 本文由 发表于 2020年10月10日 03:59:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/64286528.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定