I'm using a String
like:
String message = "%%NA开发者_如何转开发ME 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?
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);
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);
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')
Rythm a java template engine now released with an new feature called String interpolation mode which allows you do something like:
String result = Rythm.render("@name is inviting you", "Diana");
The above case shows you can pass argument to template by position. Rythm also allows you to pass arguments by name:
Map<String, Object> args = new HashMap<String, Object>();
args.put("title", "Mr.");
args.put("name", "John");
String result = Rythm.render("Hello @title @name", args);
Note Rythm is VERY FAST, about 2 to 3 times faster than String.format and velocity, because it compiles the template into java byte code, the runtime performance is very close to concatentation with StringBuilder.
Links:
- Check the full featured demonstration
- read a brief introduction to Rythm
- download the latest package or
- fork it
To replace a string character with another string using StringUtil.Replace, I tried following and it's working fine for me to replace multiple string values from a single string.
String info = "[$FIRSTNAME$][$LASTNAME$][$EMAIL$]_[$ADDRESS$]";
String replacedString = StringUtil.replace(info, new String[] { "[$FIRSTNAME$]","[$LASTNAME$]","[$EMAIL$]","[$ADDRESS$]" }, new String[] { "XYZ", "ABC" ,"abc@abc.com" , "ABCD"});
This will replace the String value of info with newly provided value...
精彩评论