This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes How to replace values in a string? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to replace values in a string?" Watch "How to replace values in a string?" New topic

How to replace values in a string?

Ajoo Bar
Ranch Hand

Joined: Mar 28, 2011
Posts: 30

I am trying to figure out how to do this

I have these properties in my property file
For example
Message1 = My First Name is &1 and my Last Name is &2
Message2 = &1 I live in &3

&1= John
&3= Florida

In my java code I read these properties from file
String message1 = My First Name is &1 and my Last Name is &2

I want to replace the ampersands with &1 and &2 in the message

The above message will look like-- My First Name is John and my Last Name is Font
And if I read message2 the Message will be John lives in Florida

How do I do that?

Amit Bhargava

Joined: May 20, 2011
Posts: 20
Try using the String.replaceAll() method. Refer to the Java API for details.
Winston Gutkowski

Joined: Mar 17, 2011
Posts: 7892

Ajoo Bar wrote:I want to replace the ampersands with &1 and &2 in the message
How do I do that?

Well, first you ShowSomeEffort. What have you written so far, and what results are you getting?

The policy here is not to simply hand out ready-made code.


Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
Manoj Kumar Jain
Ranch Hand

Joined: Aug 22, 2008
Posts: 191

You need not to replace the string, I think you should append the string like

Do not wait to strike till the iron is hot; but make it hot by striking....
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11350

you can't replace values in a String. Strings are immutable - once they are created, they can never be changed.

HOWEVER, you can use various methods of the String class to create a NEW String that looks like what you want, using the old String as a sort of starting point...

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Paul Clapham

Joined: Oct 14, 2005
Posts: 18570

I wouldn't do that. I would just use the MessageFormat class which is part of the standard Java API and which is designed to do exactly that.
I agree. Here's the link:
subject: How to replace values in a string?