File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

Win a copy of Head First Android this week in the Android forum!
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: 31

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: 8661

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: 193

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: 11814

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: 19692

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.
It is sorta covered in the JavaRanch Style Guide.
subject: How to replace values in a string?
jQuery in Action, 3rd edition