[英]Replacing smiley codes in strings
我在字符串中插入了笑脸。 我已经以某种格式对表情符号进行了编码,当我在组件中显示字符串之前,我需要用HTML img标签替换所有出现的表情符号,以便它们以图像形式显示。 这是我笑脸的格式-
&:) ==> smile
&:O ==> shocked
&:( ==> sad
etc...
所以说我有以下字符串-
Did you hear the news &:O. I won a million dollars!! &:)
我需要找到,然后用HTML替换所有的笑脸代码,例如
<img src='file:C:/images/sad.png'/>
对于要替换的每种笑脸类型,最好使用String.replaceAll(String what, String withWhat)
我认为最好使用String.replace而不是String.replaceAll
这样您就不必处理转义的正则表达式模式了……它只是一个字面的替换。
在某处定义:
static HashMap<String, String> smileys = new HashMap<String, String>();
然后用表情符号(字符串)及其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'/>");
替换笑脸是通过用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.