代码之家  ›  专栏  ›  技术社区  ›  Ivan

如何在scala中使用java.string.format?

  •  319
  • Ivan  · 技术社区  · 14 年前

    我想用一个 .format 字符串的方法。但是,如果在字符串中放置% 1、% 2等,则将JavaUTI.UnNoNyFraseExchange异常指向指向一个令人困惑的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 回复  |  直到 6 年前
        1
  •  301
  •   Xavier Guihot    6 年前

    虽然以前所有的回答都是正确的,但它们都是Java语言。下面是一个scala示例:

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

    我还有一篇关于 making format like Python's % operator 那可能有用。

        2
  •  298
  •   TM. Randy Simon    10 年前

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

    以下是正确使用此功能的示例:

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

        3
  •  127
  •   Peter Mortensen icecrime    10 年前

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

    在%之后指定值的格式。例如,对于十进制整数,它是 d ,对于字符串 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
    
        4
  •  70
  •   Engin ArdÄ±ç    11 年前

    你可以用这个;

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

    输出:

    A、B、C

        5
  •  13
  •   JacquesB    14 年前

    另请注意,scala使用许多方法扩展字符串(通过隐式转换到predef引入的wrappedString),因此您也可以执行以下操作:

    val formattedString = "Hello %s, isn't %s cool?".format("Ivan", "Scala")
    
        6
  •  11
  •   Basil Bourque    9 年前

    官方的参考是班级 Formatter .

        7
  •  10
  •   Xavier Guihot    6 年前

    在斯卡拉2.10

    val name = "Ivan"
    val weather = "sunny"
    
    s"Hello $name, it's $weather today!"
    
        8
  •  3
  •   PRO_gramista    9 年前

    这是一份清单 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
    
        9
  •  2
  •   NixRam    12 年前

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

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

        10
  •  1
  •   Reid Spencer    9 年前

    虽然@londo提到了scala的“s”字符串插入器,但我认为scala的 "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 用前缀为字母“f”的字符串定义。这是“f”(格式化)字符串插入器。
    • “f”字符串插值器使用 java.util.Formatter
    • java.lang.String.format 使用相同的 java.util.formatter格式设置工具

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

        11
  •  0
  •   Shivansh    8 年前

    在scala中,对于字符串插值 $ 这不仅节省了一天的时间,而且使我们的生活更加轻松:

    例如: 您需要定义一个函数,该函数接受输入的名称和年龄,并用名称和年龄打招呼。 可以这样写:

    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