首页 > 解决方案 > 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;

当数组中的参数数量与消息中的不同时,我想要一个例外。

谢谢你。

标签: java

解决方案


作为 JDK 一部分的MessageFormat类完全符合您的要求。

String message   = "Hello {0}, the max amount is {1}, {2} ..." ;
String formatted = MessageFormat.format(message, string1, string2, string3);

推荐阅读