在java中格式化具有由冒号标识的变量的字符串

kum*_*nny 3 java string format

我有一个Stringid 值的占位符

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

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

Output url" -> /student/230/"

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

deH*_*aar 5

如果这个占位符: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);
}
Run Code Online (Sandbox Code Playgroud)

输出:

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);
}
Run Code Online (Sandbox Code Playgroud)