首页 文章

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

提问于
浏览
315

我正在尝试使用字符串的 .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 .

11 回答

  • 11

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

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

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

  • 2

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

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

    我还有一篇关于making format like Python's % operator的博客文章可能有用 .

  • 298

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

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

    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所提到的,如果需要,您将在文档中看到可以更改默认参数排序 . 但是,您可能只需要/想要这样做的唯一时间就是您多次使用相同的参数 .

  • 1

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

    您可以在%之后指定值的格式 . 例如,对于十进制整数,它是 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
    
  • 3

    你可以用这个;

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

    输出:

    a b b c

  • 0

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

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

    官方参考是Formatter类 .

  • 127

    在Scala 2.10中

    val name = "Ivan"
    val weather = "sunny"
    
    s"Hello $name, it's $weather today!"
    
  • 300

    虽然@Londo提到Scala 's 1146351 string interpolator, I think Scala' s "f" string interpolator与原始问题更相关 . 在其他响应中使用了一些时间的例子也可以这样编写(因为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 定义了一个以字母_1146356为前缀的字符串 . 这是"f"(格式化)字符串插值器 .

    • "f"字符串插补器使用 java.util.Formatter

    • java.lang.String.format 使用相同的 java.util.Formatter

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

  • 8

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

    For Example: 您想要定义一个接受输入名称和年龄的函数,并使用名称说出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
    

相关问题