字符串模版替换的方法MessageFormat.format(String pattern, Object ... arguments)

MessageFormat.format(String pattern, Object ... arguments)

MessageFormat.format(NewOrderConstant.PAY_SCHEMA,
        URLEncoder.encode(MessageFormat.format(NewOrderConstant.RESULT_SCHEME, String.valueOf(orderId)), HTTP.UTF_8),
        URLEncoder.encode(MessageFormat.format(NewOrderConstant.RESULT_SCHEME, String.valueOf(orderId)), HTTP.UTF_8),
        URIUtil.encodeQuery(shopBO.getShopName(), HTTP.UTF_8),
        this.toStringWithRemoveTrailingZeros(huiAmount),
        NewOrderConstant.BIZ_ORDER_TYPE_OEDER,
        String.valueOf(orderId),
        String.valueOf(shopId),
        noHuiAmount == null ? "0" : this.toStringWithRemoveTrailingZeros(noHuiAmount),
        (shopBO.getType() == ShopTypeCode.IntellRestaurant_PRE_PAY || shopBO.getType() == ShopTypeCode.HBT_PRE_PAY) ? 1 : 0,
        URLEncoder.encode("{supportVoucher:" + shopBO.getHuiType() + "}", HTTP.UTF_8));

以下为代码实现:

其实这个实现就是使用了MessageFormat这个类;

String content = "ab,cc,{名称},{密码},{日期},dd,ff";

String array[] = {userName, password, format.format(new Date())};
content = MessageFormat.format(content, array);

​ 解释如下:

​ content 中需要被替换的就是{}中的参数,array数组中存放的是对应的要替换的参数;使用MessageFormat方法的时候,需要要将这些参数的个数匹配正确,并且数序要指定,否则匹配出错。这样就实现了参数的替换。很简单,也很死板。

MessageFormat:出自java.text包中;

我们可以自己打开jdk源代码读一下他的实现方式。

本文转自https://blog.csdn.net/qq_20906499/article/details/51436732

猜你喜欢

转载自www.cnblogs.com/snake107/p/12047295.html