简体   繁体   English

替换字符串中的笑脸代码

[英]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. 我已经以某种格式对表情符号进行了编码,当我在组件中显示字符串之前,我需要用HTML img标签替换所有出现的表情符号,以便它们以图像形式显示。 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 我需要找到,然后用HTML替换所有的笑脸代码,例如

<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: 然后用表情符号(字符串)及其html表示形式填充它:

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: 替换笑脸是通过用html表示形式替换每次出现的笑脸代码来完成的,只需像这样循环哈希图即可:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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