MessageFormat.format使用方法

MessageFormat.format用来格式化一个消息,通常是一个字符串。

例如: 

 String str = "{0},{1},{2}''{3}'','{4}'";
 String b = MessageFormat.format(str, "1","2","3","4","5");
 System.out.println(b);

  输出:1,2,3'4',{4}
String getCodeUrl = "https://open.weixin.qq.com/connect/qrconnect?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_login&state={2}#wechat_redirect";
String appId = “11111”;
String redirectUri = “22222”;
String state = “OPEN”;
return MessageFormat.format(getCodeUrl, appId, redirectUri, state);

输出结果:https://open.weixin.qq.com/connect/qrconnect?appid=11111&redirect_uri=22222&response_type=code&scope=snsapi_login&state=OPEN#wechat_redirect

 MessageFormat.format是根据顺序和占位符来插入的,1对应{0},2对应{1},3对应{2}。如果替换后需要加上单引号,像‘4’这样的,就需要在占位符上面对应加上两个单引号,这样才能准确转化为相应。如果加上一个单引号,结果就不会替换,最后输出是占位符本身{4}。

    /**
     * Creates a MessageFormat with the given pattern and uses it
     * to format the given arguments. This is equivalent to
     * <blockquote>
     *     <code>(new {@link #MessageFormat(String) MessageFormat}(pattern)).{@link #format(java.lang.Object[], java.lang.StringBuffer, java.text.FieldPosition) format}(arguments, new StringBuffer(), null).toString()</code>
     * </blockquote>
     *
     * @param pattern   the pattern string
     * @param arguments object(s) to format
     * @return the formatted string
     * @exception IllegalArgumentException if the pattern is invalid,
     *            or if an argument in the <code>arguments</code> array
     *            is not of the type expected by the format element(s)
     *            that use it.
     */
    public static String format(String pattern, Object ... arguments) {
        MessageFormat temp = new MessageFormat(pattern);
        return temp.format(arguments);
    }

从源码中可以看出每调用一次MessageFormat.format就会实例化一次MessageFormat,实例化后只能使用一次,所以,如果要多次格式同一个模式的字符串,那么创建一个MessageFormat实例再执行格式化操作比较好:

 String str = "{0},{1},{2}";
 MessageFormat messageFormat = new MessageFormat(str);
 String[] array = {"1","2","3"};
 String c = messageFormat.format(array);
 System.out.println(c);

 输出:1,2,3

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值