简体   繁体   English

用Java迭代格式化字符串的特定部分

[英]Iteratively formatting the specific parts of a String in Java

I know that in java we can do something like: 我知道在Java中我们可以做类似的事情:

String s = "I am a %s %s"

s = s.format("format", "string")

I was wondering if it is possible to replace the occurance of only one %s at a time and furthermore if I can give names to these such as %1 , %2 . 我想知道是否可以一次只替换一个%s ,而且我是否可以给它们命名,例如%1%2 What I am trying to achieve is having a huge html string where each method will complete a specific part of that string. 我想要实现的是拥有一个巨大的html字符串,其中每个方法都将完成该字符串的特定部分。 The string will be completed in an iterative way and I want to make sure that each method completes its own part. 该字符串将以迭代方式完成,我想确保每个方法都完成自己的部分。

Technically, you can use simply String.replace : 从技术上讲,您可以简单地使用String.replace

s = s.replace("%1", value1);
s = s.replace("%2", value2);

Depending on what you want to do, you may or may not have to think about security and people using this to inject malicious scripts in your html. 根据您要执行的操作,您可能必须考虑安全性,也可能不必考虑安全性,并且有人使用它来将恶意脚本注入html中。 In the latter case, sanitizing the user input is top priority. 在后一种情况下,对用户输入进行清理是重中之重。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM