如何在Scala中使用java.String.format? [英] How to use java.String.format in Scala?

查看:164
本文介绍了如何在Scala中使用java.String.format?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用字符串的 .format 方法。但是,如果我将%1,%2等放在字符串中,则会抛出java.util.UnknownFormatConversionException,指向一个令人困惑的Java源代码块:

  private void checkText(String s){

int idx;

//如果给定字符串中有任何'%',我们得到一个不好的格式
//说明符。
if((idx = s.indexOf('%'))!= -1){
char c =(idx> s.length() - 2?'%':s.charAt (idx + 1));
抛出新的UnknownFormatConversionException(String.valueOf(c));






$ b

从这里我明白了字符被禁止。如果是这样,那么我应该使用什么参数占位符?



我使用
pre $ val placeholder =你好%s,不是很酷吗?
val formatted = placeholder.format(Ivan,Scala)

我也有一篇关于制作格式就像Python的运算符可能是有用的。


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?

I use Scala 2.8.

解决方案

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")

I also have a blog post about making format like Python's % operator that might be useful.

这篇关于如何在Scala中使用java.String.format?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆