简体   繁体   中英

Iteratively formatting the specific parts of a String in Java

I know that in java we can do something like:

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 . What I am trying to achieve is having a huge html string where each method will complete a specific part of that string. 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 :

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. In the latter case, sanitizing the user input is top priority.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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