Cemre Mengü
Cemre Mengü

Reputation: 18754

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.

Upvotes: 0

Views: 163

Answers (1)

Cyrille Ka
Cyrille Ka

Reputation: 15523

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.

Upvotes: 1

Related Questions