• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to replace values in a string?

 
Ajoo Bar
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try using the String.replaceAll() method. Refer to the Java API for details.
 
Winston Gutkowski
Bartender
Pie
Posts: 10509
64
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Manoj Kumar Jain
Ranch Hand
Posts: 198
Java Linux Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need not to replace the string, I think you should append the string like



 
fred rosenberger
lowercase baba
Bartender
Posts: 12186
34
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
Paul Clapham
Sheriff
Posts: 21322
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic