java - 在java中格式化具有由冒号标识的变量的字符串
问题描述
我有String
一个 id 值的占位符
"Input url -> "/student/:id/"
我需要插入这样一个值才能使结果看起来像
Output url" -> /student/230/"
我们可以使用 String 的 format() 方法吗,我不想在我的 url 中使用 %d,只是想要一种替换 :id 变量的方法。
解决方案
如果此占位符: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/
推荐阅读
- javascript - Socket.io 删除了我的 javascript 对象的一些数据
- ios - 如何在swift3 iOS中将文本写入保存在服务器上的文件
- solr - 如何让 SolrCloud 使用 HTTPS 创建集合?
- v8 - 在 linux 平台上编译 V8 失败
- python - __init__() 接受 1 个位置参数,但在一个非常简单的表单函数上给出了 2 个错误
- excel - 如何从 Excel 数据填充用户表单中的组合框下拉列表?
- file - .nii 扩展名的文件有分隔符吗?
- mysql - 此查询也显示昨天和今天的数据,但我只想要今天的数据
- jquery - 嵌套 $(document).ready() 以测试嵌套页面是否处于活动状态
- c# - Autofac 无法解析我的注册通用服务