如何在 Scala 中使用 java.String.format? [英] How to use java.String.format in Scala?
问题描述
我正在尝试使用字符串的 .format
方法.但是,如果我将 %1、%2 等放在字符串中,则会抛出 java.util.UnknownFormatConversionException 指向一个令人困惑的 Java 源代码片段:
I am trying to use a .format
method of a string. But if I place %1, %2, etc. in the string, java.util.UnknownFormatConversionException is thrown pointing to a confusing Java source code piece:
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));
}
}
由此我了解到 %
字符是被禁止的.如果是这样,那么我应该为参数占位符使用什么?
From this I understand that %
char is forbidden. If so, then what should I use for argument placeholders?
我使用 Scala 2.8.
推荐答案
虽然之前的所有回答都是正确的,但它们都是用 Java 编写的.这是一个 Scala 示例:
While all the previous responses are correct, they're all in Java. Here's a Scala example:
val placeholder = "Hello %s, isn't %s cool?"
val formatted = placeholder.format("Ivan", "Scala")
我还有一篇关于制作format
就像 Python 的 %
操作符,可能很有用.
I also have a blog post about making format
like Python's %
operator that might be useful.
这篇关于如何在 Scala 中使用 java.String.format?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!