2012-03-24 42 views
0

我將笑臉插入字符串中。我以某種格式編碼了表情符號,並且在顯示組件中的字符串之前,我需要用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'/>

回答

2

定義這個地方:

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表示,只是像這樣循環hashmap:

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

乾杯隊友,比switch語句或if語句的加載更優雅。假設我在笑臉代碼中的')'之前需要雙反斜槓。 – csss 2012-03-24 14:26:26

4

你是最好的使用String.replaceAll(String what, String withWhat)每種類型的笑臉你ar Ë試圖取代

+1

只記得用'\'來轉義'('和')'這樣的字符。 – GavinCattell 2012-03-24 14:12:18

+0

簡短而相關! 我只是想指出,使用這種方法,你必須確保沒有笑臉開始於另一個笑臉的結束,因爲這可能會產生不良結果,當他們被解析。 – neXus 2012-03-24 14:12:58

+0

@亞歷克斯:好吧,我要去這裏 – csss 2012-03-24 14:17:30

4

我認爲你最好使用String.replace而不是String.replaceAll,所以你不必處理轉義的正則表達式模式......它只是一個字面替換。