繁体   English   中英

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

[英]How to use java.String.format in 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));
    }
}

据我所知, % char是被禁止的。 如果是这样,那么我应该将什么用于参数占位符?

我使用Scala 2.8。

虽然之前的所有回复都是正确的,但它们都是Java语言。 这是一个Scala示例:

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

我还有一篇关于制作类似Python的%运算符format的博客文章可能很有用。

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

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

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

您将始终使用%后跟其他一些字符让方法知道它应该如何显示字符串。 %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."

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

并且,正如BalusC所提到的,如果需要,您将在文档中看到可以更改默认参数排序。 但是,您可能只需要/想要这样做的唯一时间就是您多次使用相同的参数。

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

您可以在%之后指定值的格式。 例如,对于十进制整数,它是d ,对于String,它是s

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

输出:

Hello, world on line 20

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

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

输出:

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

你可以用这个;

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

输出:

ABBC

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

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

官方参考是Formatter类。

在Scala 2.10中

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

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

这是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

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

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

虽然@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?

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

  • formatted是使用带有字母“f”前缀的字符串定义的。 这是“f”(格式化)字符串插值器。
  • “f”字符串插值器使用java.util.Formatter
  • java.lang.String.format使用相同的java.util.Formatter

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

在scala中,对于字符串插值,我们有$可以节省一天,让我们的生活变得轻松:

例如:您想要定义一个接受输入名称和年龄的函数,并用名称表示Hello并说明其年龄。 这可以这样写:

def funcStringInterpolationDemo(name:String,age:Int)=s"Hey ! my name is $name and my age is $age"

因此,当你调用这个函数时:像这样:

funcStringInterpolationDemo("Shivansh",22)

它的输出将是:

Hey ! my name is Shivansh and my age is 22

您可以编写代码以在同一行中更改它,例如,如果您想要添加10年的年龄!

然后功能可以是:

def funcStringInterpolationDemo(name:String,age:Int)=s"Hey ! my name is $name and my age is ${age+10}"

现在输出将是:

Hey ! my name is Shivansh and my age is 32

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM