如何在 Scala 中使用 java.String.format?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3695230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 03:34:46  来源:igfitidea点击:

How to use java.String.format in Scala?

javastringscalaformat

提问by Ivan

I am trying to use a .formatmethod 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:

我正在尝试使用.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));
    }
}

From this I understand that %char is forbidden. If so, then what should I use for argument placeholders?

由此我明白%char 是被禁止的。如果是这样,那么我应该为参数占位符使用什么?

I use Scala2.8.

我使用Scala2.8。

采纳答案by pr1001

While all the previous responses are correct, they're all in Java. Here's a Scala example:

虽然之前的所有回答都是正确的,但它们都是用 Java 编写的。这是一个 Scala 示例:

val placeholder = "Hello %s, isn't %s cool?"
val formatted = placeholder.format("Ivan", "Scala")

I also have a blog post about making formatlike Python's %operatorthat might be useful.

我还有一篇关于制作format像 Python 的%操作符的博客文章,可能会有用。

回答by TM.

You don't need to use numbers to indicate positioning. By default, the position of the argument is simply the order in which it appears in the string.

您不需要使用数字来表示定位。默认情况下,参数的位置只是它在字符串中出现的顺序。

Here's an example of the proper way to use this:

以下是正确使用此方法的示例:

String result = String.format("The format method is %s!", "great");
// result now equals  "The format method is great!".

You will always use a %followed by some other characters to let the method know how it should display the string. %sis probably the most common, and it just means that the argument should be treated as a string.

您将始终使用%后跟一些其他字符来让方法知道它应该如何显示字符串。 %s可能是最常见的,它只是意味着应该将参数视为字符串。

I won't list every option, but I'll give a few examples just to give you an idea:

我不会列出所有选项,但我会举几个例子来给你一个想法:

// 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."

String.formatjust uses a java.util.Formatter, so for a full description of the options you can see the Formatter javadocs.

String.format只使用java.util.Formatter,因此有关选项的完整说明,您可以查看Formatter javadocs

And, as BalusC mentions, you will see in the documentation that is possible to change the default argument ordering if you need to. However, probably the only time you'd need / want to do this is if you are using the same argument more than once.

而且,正如 BalusC 所提到的,您将在文档中看到可以根据需要更改默认参数顺序。但是,可能您唯一需要/想要这样做的时候是您不止一次使用相同的参数。

回答by OscarRyz

Instead of looking at the source code, you should read the javadoc String.format()and Formatter syntax.

您应该阅读 javadoc String.format()Formatter 语法,而不是查看源代码。

You specify the format of the value after the %. For instance for decimal integer it is d, and for String it is s:

在 % 后指定值的格式。例如,对于十进制整数,它是d,对于字符串,它是s

String aString = "world";
int aInt = 20;
String.format("Hello, %s on line %d",  aString, aInt );

Output:

输出:

Hello, world on line 20

To do what you tried (use an argument index), you use: *n*$,

做你尝试(使用参数索引),您可以使用:*n*$

String.format("Line:%2$d. Value:%1$s. Result: Hello %1$s at line %2$d", aString, aInt );

Output:

输出:

Line:20. Value:world. Result: Hello world at line 20

回答by denis phillips

Also note that Scala extends String with a number of methods (via implicit conversion to a WrappedString brought in by Predef) so you could also do the following:

另请注意,Scala 使用多种方法扩展了 String(通过隐式转换为 Predef 引入的 WrappedString),因此您还可以执行以下操作:

val formattedString = "Hello %s, isn't %s cool?".format("Ivan", "Scala")

回答by NixRam

Here is a list of formatters used with String.format()

这是与 String.format() 一起使用的格式化程序列表

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html

回答by Alberto Segura

The official reference is the class Formatter.

官方参考是 class Formatter

回答by Londo

In Scala 2.10

在 Scala 2.10 中

val name = "Ivan"
val weather = "sunny"

s"Hello $name, it's $weather today!"

回答by Engin Ard??

You can use this;

你可以用这个;

String.format("%1$s %2$s %2$s %3$s", "a", "b", "c");

Output:

输出:

a b b c

美国广播公司

回答by PRO_gramista

This is a list of what String.formatcan do. The same goes for printf

这是String.format可以做什么的列表。同样适用于printf

int i = 123;
o.printf( "|%d|%d|%n" ,       i, -i );      // |123|-123|
o.printf( "|%5d|%5d|%n" ,     i, -i );      // |  123| –123|
o.printf( "|%-5d|%-5d|%n" ,   i, -i );      // |123  |-123 |
o.printf( "|%+-5d|%+-5d|%n" , i, -i );      // |+123 |-123 |
o.printf( "|%05d|%05d|%n%n",  i, -i );      // |00123|-0123|

o.printf( "|%X|%x|%n", 0xabc, 0xabc );      // |ABC|abc|
o.printf( "|%04x|%#x|%n%n", 0xabc, 0xabc ); // |0abc|0xabc|

double d = 12345.678;
o.printf( "|%f|%f|%n" ,         d, -d );    // |12345,678000|     |-12345,678000|
o.printf( "|%+f|%+f|%n" ,       d, -d );    // |+12345,678000| |-12345,678000|
o.printf( "|% f|% f|%n" ,       d, -d );    // | 12345,678000| |-12345,678000|
o.printf( "|%.2f|%.2f|%n" ,     d, -d );    // |12345,68| |-12345,68|
o.printf( "|%,.2f|%,.2f|%n" ,   d, -d );    // |12.345,68| |-12.345,68|
o.printf( "|%.2f|%(.2f|%n",     d, -d );    // |12345,68| |(12345,68)|
o.printf( "|%10.2f|%10.2f|%n" , d, -d );    // |  12345,68| | –12345,68|
o.printf( "|%010.2f|%010.2f|%n",d, -d );    // |0012345,68| |-012345,68|

String s = "Monsterbacke";
o.printf( "%n|%s|%n", s );                  // |Monsterbacke|
o.printf( "|%S|%n", s );                    // |MONSTERBACKE|
o.printf( "|%20s|%n", s );                  // |        Monsterbacke|
o.printf( "|%-20s|%n", s );                 // |Monsterbacke        |
o.printf( "|%7s|%n", s );                   // |Monsterbacke|
o.printf( "|%.7s|%n", s );                  // |Monster|
o.printf( "|%20.7s|%n", s );                // |             Monster|

Date t = new Date();
o.printf( "%tT%n", t );                     // 11:01:39
o.printf( "%tD%n", t );                     // 04/18/08
o.printf( "%1$te. %1$tb%n", t );            // 18. Apr

回答by Reid Spencer

Although @Londo mentioned Scala's "s" string interpolator, I think Scala's "f" string interpolatoris more relevant to the original question. The example used a few time in other responses could also be written (since Scala 2.10) this way:

尽管@Londo 提到了 Scala 的“s”字符串插值器,但我认为 Scala 的“f”字符串插值器与原始问题更相关。在其他响应中多次使用的示例也可以这样编写(自 Scala 2.10 起):

scala> val name = "Ivan"
name: String = Ivan
scala> val thing = "Scala"
thing: String = Scala
scala> val formatted = f"Hello $name%s, isn't $thing%s cool?"
formatted: String = Hello Ivan, isn't Scala cool?

The connection to the original question is to be aware that:

与原始问题的联系是要注意:

  • formattedis defined with a string that is prefixed with the letter "f". This is the "f" (formatting) string interpolator.
  • The "f" string interpolator uses java.util.Formatter
  • java.lang.String.formatuses the same java.util.Formatter
  • formatted用一个以字母“f”为前缀的字符串定义。这是“f”(格式化)字符串插值器。
  • “f”字符串插值器使用 java.util.Formatter
  • java.lang.String.format使用相同的 java.util.Formatter

The nice thing about string interpolation is that it lets you see which variable is being substituted directly into the string instead of having to match it with the arguments to the String.formatmethod.

字符串插值的好处在于,它可以让您看到哪个变量被直接替换到字符串中,而不必将其与String.format方法的参数进行匹配。