Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a word in a String?

Tags:

java

string

I'm using a String like:

String message = "%%NAME is inviting you";

I am using message.replaceAll("%%NAME", me); where me is a String. This line of code is not working for me. I was wondering what I was doing wrong?

like image 933
Sean Avatar asked Sep 28 '11 01:09

Sean


3 Answers

Code looks more or less OK, though there may be some syntax issues. Here's a working example:

String message = "%%NAME is inviting you.";
String name = "Diana";
String result = message.replaceAll("%%NAME", name);
like image 157
martyman Avatar answered Nov 03 '22 01:11

martyman


I would suggest using the format method instead of replaceAll in this case.

UPDATE - Example

String template = "%s is inviting you";
String name = "Bob";
String result = String.format(template, name);
like image 40
Snowy Coder Girl Avatar answered Nov 03 '22 01:11

Snowy Coder Girl


String message = "%%name is inviting you";
String uname = "Keyser Sose";
message.replaceAll("%%name", uname);

...will not modify 'message' because Strings (in java) are immutable

String message = "%%name is inviting you";
String uname = "Keyser Sose";
message = message.replaceAll("%%name", uname);

..WILL work. (Note the re-assignment of 'message')

like image 43
claymore1977 Avatar answered Nov 02 '22 23:11

claymore1977