aspose file tools*
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 The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript 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
Author

How to replace values in a string?

Ajoo Bar
Ranch Hand

Joined: Mar 28, 2011
Posts: 30
Hi,

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
&2=Font
&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?


Thanks
Ajoo
Amit Bhargava
Greenhorn

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

Joined: Mar 17, 2011
Posts: 7676
    
  19

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.

Winston


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
Bartender

Joined: Oct 02, 2003
Posts: 11246
    
  16

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
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

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?