簡體   English   中英

替換字符串中的笑臉代碼

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM