首页 > 解决方案 > 在java中格式化具有由冒号标识的变量的字符串

问题描述

我有String一个 id 值的占位符

"Input url -> "/student/:id/"

我需要插入这样一个值才能使结果看起来像

Output url" -> /student/230/"

我们可以使用 String 的 format() 方法吗,我不想在我的 url 中使用 %d,只是想要一种替换 :id 变量的方法。

标签: javastringformat

解决方案


如果此占位符:id已修复且仅在您的String源中出现一次,那么您可以简单地将其替换为一个值。看这个例子:

public static void main(String[] args) {
    // provide the source String with the placeholder
    String source =  "/student/:id/";
    // provide some example id (int here, possibly different type)
    int id = 42;
    // create the target String by replacing the placeholder with the value
    String target = source.replace(":id", String.valueOf(id));
    // and print the result
    System.out.println(target);
}

输出:

/student/42/

推荐阅读