wood burning stoves
The moose likes Java in General and the fly likes element substitution into a string Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "element substitution into a string" Watch "element substitution into a string" New topic

element substitution into a string

Dan R Tarrant

Joined: Dec 01, 2004
Posts: 1
I'm looking for approaches and solutions to element substitution into a string.

For example a string with elements to be will look like.

Dear ${first_name} ${last_name},

Welcome to our Game Club. We will contact you via you email ${email}.

Where I need to substitute values for the elements that are formated as ${element_name}.
So in the example above the elements to be substituted are:
Joel McNary

Joined: Aug 20, 2001
Posts: 1824

have you checked out java.lang.String,%20java.lang.String)" target="_blank" rel="nofollow">replaceAll in java.lang.String?

Be forewarned, the pattern is a regular expression, so it's trickier than the method first appears (but only a little bit trickier....)

Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
marc weber

Joined: Aug 31, 2004
Posts: 11343

If you're using Java 1.5, then String has a new method, replace(CharSequence target, CharSequence replacement).

But how exactly you might implement this depends on the bigger picture.

For example, if you have each member's information stored as instances of a small class called Member, and Member instances are all stored in some sort of collection like an ArrayList, then you could iterate through the List, and generate custom Strings for each Member. Under this model, the fragment might look something like this...

[ December 01, 2004: Message edited by: marc weber ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
JDK 5 has printf() on PrintStream and PrintWriter that do C-like substitutions. Earlier JDKs have MessageFormat.

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
I agree. Here's the link: http://aspose.com/file-tools
subject: element substitution into a string
It's not a secret anymore!