从数据库获取URL后如何进行字符串插值替换参数
替换URL模板中的占位符方法
以下是几种主流编程语言的实现方式,直接就能用:
C# 实现
假设从数据库取出的URL模板存在urlTemplate变量,要替换的id值存在userId变量:
string urlTemplate = "http://localhost/Account/Get/{id}"; int userId = 123; // 方法1:直接字符串替换 string finalUrl = urlTemplate.Replace("{id}", userId.ToString()); // 方法2:用string.Format(适合多占位符场景) string formattedTemplate = urlTemplate.Replace("{id}", "{0}"); string finalUrl = string.Format(formattedTemplate, userId);
Python 实现
Python支持命名占位符,直接用str.format()就能匹配模板里的{id}:
url_template = "http://localhost/Account/Get/{id}" user_id = 123 final_url = url_template.format(id=user_id)
Java 实现
String urlTemplate = "http://localhost/Account/Get/{id}"; int userId = 123; // 方法1:直接替换 String finalUrl = urlTemplate.replace("{id}", String.valueOf(userId)); // 方法2:用MessageFormat适配多占位符 String formattedTemplate = urlTemplate.replace("{id}", "{0}"); String finalUrl = MessageFormat.format(formattedTemplate, userId);
核心逻辑很简单:要么直接把模板里的{id}字符串替换成变量值,要么把模板转成对应语言支持的格式化格式,再用内置的格式化方法传入变量。
内容的提问来源于stack exchange,提问作者carlosm
相关产品推荐
相关产品推荐

