java - JAVA - 如何替换字符串中的标记
问题描述
我有一个像这样的字符串:
String message = "Hello {0}, the max amount is {1}, {2} ..." ;
替换 {0}、{1}、{2} 的消息在字符串数组中:
String[] strings = new String[1];
strings[0] = object.CONSTANTE;
strings[1] = object.CONSTANTE1;
strings[2] = object.CONSTANTE2;
当数组中的参数数量与消息中的不同时,我想要一个例外。
谢谢你。
解决方案
作为 JDK 一部分的MessageFormat类完全符合您的要求。
String message = "Hello {0}, the max amount is {1}, {2} ..." ;
String formatted = MessageFormat.format(message, string1, string2, string3);
推荐阅读
- javascript - HighChart 标题文本实现的 HTML 样式不适用于导出文件
- sql - 如何在sql数据库服务器上的表中设置最大数量
- gmail - 如何从 gmail api history.list 中过滤掉草稿消息
- javascript - 从静态网页访问 github
- javascript - 在 HTML 文件的 body 或 head 中创建的 JS 脚本可以直接在 CSS 代码中使用吗?
- apache - cpan 无法安装 mod_fcgid,不知道是什么
- angular - 如何在角材料下拉角5中实现全选
- java - 将对象转换为地图:Cast 与 ObjectMapper
- amazon-web-services - 实时获取预签名 URL 的带宽使用情况?
- java - getResourceAsStream() 在 Eclipse 中工作正常,但在 jar 中失败