简体   繁体   中英

Replacing smiley codes in strings

I am inserting smileys into strings. I have encoded the smileys in a certain format and when before I display the string in a component I need to replace all occurrences of the smiley codes with HTML img tags so they will show up as images. So here is the format of my smileys -

&:) ==> smile

&:O ==> shocked

&:( ==> sad

etc...

So say I have the following string -

Did you hear the news &:O. I won a million dollars!! &:)

I need to find, and then replace all the smiley codes with HTML like

<img src='file:C:/images/sad.png'/>

对于要替换的每种笑脸类型,最好使用String.replaceAll(String what, String withWhat)

我认为最好使用String.replace而不是String.replaceAll这样您就不必处理转义的正则表达式模式了……它只是一个字面的替换。

define this somewhere:

static HashMap<String, String> smileys = new HashMap<String, String>();

then fill it with the smileys (String) and their html representation:

smileys.put("&:)", "<img src='file:C:/images/sad.png'/>");
smileys.put("&:O", "<img src='file:C:/images/sad.png'/>");
smileys.put("&:(", "<img src='file:C:/images/sad.png'/>");

replacing smileys is done by replacing every occurrence of a smiley code by its html representation, just loop the hashmap like this:

public String replaceSmileys(String text){
    for(Entry<String, String> smiley : smileys.entrySet())
        text = text.replaceAll(smiley.getKey(), smiley.getValue());
    return text;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM