You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中如何实现支持多参数输入的字符串占位符填充函数?

可行,具体实现方案如下

Java的可变参数(varargs)特性可以完美实现你想要的调用方式,配合MessageFormat.format就能兼容原有的占位符逻辑,甚至还能扩展支持SourcePawn风格的%s占位符。

1. 基础实现(兼容原{1}类占位符)

直接重载或修改原函数,让它接受可变参数,内部自动转成MessageFormat需要的参数数组:

import java.text.MessageFormat;
import java.util.List;

public class MessageUtils {
    // 新增支持可变参数的版本,符合你的调用习惯
    public static String fillInArguments(String pattern, Object... args) {
        return MessageFormat.format(pattern, args);
    }

    // 保留原有的List参数版本(如需兼容旧代码)
    public static String fillInArguments(String pattern, List<Object> args) {
        return MessageFormat.format(pattern, args.toArray());
    }
}

调用示例

// 假设已有User类实例
User user = new User("Alice", 5);
String msg = MessageUtils.fillInArguments(
    "Hello {0}! You have {1} unread messages!",
    user.getName(),
    user.getUnreadMsgs()
);
// 输出:Hello Alice! You have 5 unread messages!

注意:MessageFormat的占位符默认从{0}开始计数,如果你语言文件里用的是{1}开头,需要把占位符改成{0}起始,或者在函数里加一个简单的替换逻辑(比如把{n}替换成{n-1})。

2. 扩展实现(支持SourcePawn的%s占位符)

如果想直接用%s作为占位符,可以先把字符串中的%s按顺序替换为{0}、{1}...再调用MessageFormat.format:

import java.text.MessageFormat;

public class MessageUtils {
    public static String fillInArguments(String pattern, Object... args) {
        // 把%s按顺序替换为对应的索引占位符
        StringBuilder patternBuilder = new StringBuilder(pattern);
        int argIndex = 0;
        int pos;
        while ((pos = patternBuilder.indexOf("%s")) != -1) {
            patternBuilder.replace(pos, pos + 2, "{" + argIndex++ + "}");
        }
        return MessageFormat.format(patternBuilder.toString(), args);
    }
}

调用示例

String msg = MessageUtils.fillInArguments(
    "%s has thanked %s",
    "Bob",
    "Charlie"
);
// 输出:Bob has thanked Charlie

内容的提问来源于stack exchange,提问作者technyk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 00:10:23