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

Java中使用int类型变量替换字符串内指定占位符的实现方法

误区纠正

你这里不需要使用Integer.parseInt,这个方法的作用是将字符串格式的数字转换为int类型,你当前的需求是反过来把int类型的feet、inches转为字符串嵌入模板,属于字符串拼接/替换场景,有三种常用实现方案:


方案1:直接替换原有A/B占位符

不需要修改现有模板定义,在toString方法中调用String.replace替换即可:

public class EngLength {
    private int feet;
    private int inches;
    private String lengthValue = "A ft, B in";

    public EngLength(int feet, int inches) {
        this.feet = feet;
        this.inches = inches;
    }

    public String toString() {
        // 依次替换A、B两个占位符
        return lengthValue.replace("A", String.valueOf(feet))
                          .replace("B", String.valueOf(inches));
    }
}

方案2:使用String.format规范模板(推荐)

把自定义的A/B占位符换成Java标准的格式化占位符,性能和可读性更好,模板建议定义为全局静态常量避免重复创建:

public class EngLength {
    private int feet;
    private int inches;
    // %d 为整数类型的格式化占位符
    private static final String LENGTH_TEMPLATE = "%d ft, %d in";

    public EngLength(int feet, int inches) {
        this.feet = feet;
        this.inches = inches;
    }

    public String toString() {
        // 按顺序传入参数替换占位符即可
        return String.format(LENGTH_TEMPLATE, feet, inches);
    }
}

方案3:直接字符串拼接

如果不需要复用模板,最简单的写法是直接拼接变量和固定文本:

public String toString() {
    return feet + " ft, " + inches + " in";
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 21:30:04