miladydesummer
miladydesummer

Reputation: 143

Is it possible to set a parameter inside an otherwise constant String?

I am using a set of constant Strings for text anonymization. One of the strings should go something like "[Town in the state of XX]", where XX is to be replaced later with an actual state (the rest of the string remains as is).

My question is: is there a way to do this "elegantly" (in the spirit of a SQL PreparedStatement)? Or should I just put XX and then do myString.replace("XX", "someState"), in which case, the string can no longer be a constant :(

EDIT: Just realized that String.replace returns a new String, so myString could still be a constant with this method.

Upvotes: 2

Views: 169

Answers (2)

Viktor Mellgren
Viktor Mellgren

Reputation: 4506

You can use the Formatter class

And conveniently from system out

System.out.format("My name is '%s' and i am %d years old. My party will be at '%s'.", name, years, time);

Upvotes: 0

f1sh
f1sh

Reputation: 11934

If you use %s instead of XX, then you can simply use String.format.

Upvotes: 6

Related Questions