Iva*_*van 320 java string format scala
我正在尝试使用.format
字符串的方法.但是如果我在字符串中放置%1,%2等,则会抛出java.util.UnknownFormatConversionException指向令人困惑的Java源代码段:
private void checkText(String s) {
int idx;
// If there are any '%' in the given string, we got a bad format
// specifier.
if ((idx = s.indexOf('%')) != -1) {
char c = (idx > s.length() - 2 ? '%' : s.charAt(idx + 1));
throw new UnknownFormatConversionException(String.valueOf(c));
}
}
Run Code Online (Sandbox Code Playgroud)
据此我明白,%
禁止使用char.如果是这样,那么我应该将什么用于参数占位符?
我使用Scala 2.8.
pr1*_*001 301
虽然之前的所有回复都是正确的,但它们都是Java语言.这是一个Scala示例:
val placeholder = "Hello %s, isn't %s cool?"
val formatted = placeholder.format("Ivan", "Scala")
Run Code Online (Sandbox Code Playgroud)
我还有一篇关于制作format
%
可能有用的Python 操作符的博客文章.
TM.*_*TM. 298
您无需使用数字来指示定位.默认情况下,参数的位置只是它在字符串中出现的顺序.
以下是使用此方法的正确方法示例:
String result = String.format("The format method is %s!", "great");
// result now equals "The format method is great!".
Run Code Online (Sandbox Code Playgroud)
您将始终使用a %
后跟其他一些字符让方法知道它应该如何显示字符串. %s
可能是最常见的,它只是意味着参数应该被视为一个字符串.
我不会列出所有选项,但我会举几个例子来给你一个想法:
// we can specify the # of decimals we want to show for a floating point:
String result = String.format("10 / 3 = %.2f", 10.0 / 3.0);
// result now equals "10 / 3 = 3.33"
// we can add commas to long numbers:
result = String.format("Today we processed %,d transactions.", 1000000);
// result now equals "Today we processed 1,000,000 transactions."
Run Code Online (Sandbox Code Playgroud)
String.format
只使用a java.util.Formatter
,所以有关选项的完整描述,您可以看到Formatter javadocs.
并且,正如BalusC所提到的,如果需要,您将在文档中看到可以更改默认参数排序.但是,您可能只需要/想要这样做的唯一时间就是您多次使用相同的参数.
Osc*_*Ryz 127
您应该阅读javadoc String.format()和Formatter语法,而不是查看源代码.
您可以在%之后指定值的格式.例如,对于十进制整数,它是d
,对于String,它是s
:
String aString = "world";
int aInt = 20;
String.format("Hello, %s on line %d", aString, aInt );
Run Code Online (Sandbox Code Playgroud)
输出:
Hello, world on line 20
Run Code Online (Sandbox Code Playgroud)
要执行您尝试的操作(使用参数索引),您使用:*n*$
,
String.format("Line:%2$d. Value:%1$s. Result: Hello %1$s at line %2$d", aString, aInt );
Run Code Online (Sandbox Code Playgroud)
输出:
Line:20. Value:world. Result: Hello world at line 20
Run Code Online (Sandbox Code Playgroud)
Eng*_*dıç 70
你可以用这个;
String.format("%1$s %2$s %2$s %3$s", "a", "b", "c");
Run Code Online (Sandbox Code Playgroud)
输出:
ABBC
den*_*ips 13
另请注意,Scala使用多种方法扩展String(通过隐式转换为Predef引入的WrappedString),因此您还可以执行以下操作:
val formattedString = "Hello %s, isn't %s cool?".format("Ivan", "Scala")
Run Code Online (Sandbox Code Playgroud)
小智 10
在Scala 2.10中
val name = "Ivan"
val weather = "sunny"
s"Hello $name, it's $weather today!"
Run Code Online (Sandbox Code Playgroud)