使用Java中的MessageFormat.format()格式化消息 [英] Format a message using MessageFormat.format() in Java

查看:128
本文介绍了使用Java中的MessageFormat.format()格式化消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在资源包中存储了一些消息。我正在尝试格式化这些消息,如下所示。

I have stored some messages in a resource bundle. I'm trying to format these messages as follows.

import java.text.MessageFormat;

String text = MessageFormat.format("You're about to delete {0} rows.", 5);
System.out.println(text);

假设第一个参数即实际消息存储在以某种方式检索的属性文件中。

Assume that the first parameter i.e the actual message is stored in a property file which is somehow retrieved.

第二个参数即5是一个动态值,应该放在占位符 {0} 中发生。下一行打印,

The second parameter i.e 5 is a dynamic value and should be placed in the placeholder {0} which doesn't happen. The next line prints,


您要删除{0}行。

Youre about to delete {0} rows.

占位符不会被实际参数替换。

The placeholder is not replaced with the actual parameter.

这是撇号 - 你是。我试图像往常一样逃避它,比如你虽然没有用,但仍然没有工作。要使其发挥作用需要做哪些改变?

It is the apostrophe here - You're. I have tried to escape it as usual like You\\'re though it didn't work. What changes are needed to make it work?

推荐答案

' > MessageFormat pattern String 以确保显示'字符

Add an extra apostrophe ' to the MessageFormat pattern String to ensure the ' character is displayed

String text = 
     java.text.MessageFormat.format("You''re about to delete {0} rows.", 5);
                                         ^

撇号(又名单引号) MessageFormat模式启动带引号的字符串,不会自行解释。来自 javadoc

An apostrophe (aka single quote) in a MessageFormat pattern starts a quoted string and is not interpreted on its own. From the javadoc


单个引号本身必须在整个字符串中用双引号表示。

A single quote itself must be represented by doubled single quotes '' throughout a String.

字符串 你\\ 相当于在中添加一个反斜杠字符字符串因此,唯一的区别是将生成而不是 Youre 。 (在双引号解决方案''申请之前)

The String You\\'re is equivalent to adding a backslash character to the String so the only difference will be that You\re will be produced rather than Youre. (before double quote solution '' applied)

这篇关于使用Java中的MessageFormat.format()格式化消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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