2014-04-29 35 views
0

我有一個這樣的數據庫表情列表檢查字符並將圖釋轉換爲文本? C#

id | emoticon | convert_text 

1 | :)  | e_happy 

2 | :( | e_sad 

如何檢查是否有任何字符列入表情符號列表?

如果找到,則將表情符號改爲文字。

例子:

before 
S = Smile at everyone who doesn't smile at your :) 

after 
S= Smile at everyone who doesn't smile at your e_happy 

*編輯

首先我試過每一個字拆這樣

static void Main(string[] args) 
    { 
     string value = "Smile at everyone who doesn't smile at your :)"; 
     char[] delimiter = new char[] { ' ', ',', '.' }; 

     string[] array = value.Split(delimiter, StringSplitOptions.RemoveEmptyEntries); 
     foreach (string entry in array) 
     { 
      Console.WriteLine(entry); 
     } 
     Console.ReadKey(); 
    } 

我很困惑如何檢查每個字進行的表情列表在數據庫中,並將圖釋轉換爲文本,如示例 *對不起,這是我的第一篇文章,我正在翻譯谷歌翻譯

+0

我已經更新我的問題 – Hibishi

+0

因此,第一部分是從數據庫中獲取表情圖到相應的convert_text標記。這取決於你正在使用的數據庫。你已經完成了這部分? –

+1

您可以將'emoticon'和'convert_text'存儲到'Dictionary '中,其中鍵是'表情符號'是關鍵字,'convert_text'是值。然後使用字典查找並替換單詞。 一旦你遇到問題,你會分裂字符可能會丟失,你可能需要找出一個辦法 – Ramesh

回答

0

如何使用正則表達式?

var emoticons = new Dictionary<string, string> 
{ 
    { ":)" , "smile" }, 
    { ";)" , "blink" }, 
    { ">:)", "devil" }, 
    { "@}-", "rose" } 
}; 
string value = "Smile at everyone who doesn't smile at your :)"; 
Console.WriteLine(Regex.Replace(value, 
    String.Join("|",emoticons.Select(e => Regex.Escape(e.Key)).ToArray()), 
    (match) => 
    { 
     string result = null; 
     return emoticons.TryGetValue(match.Value, out result) 
      ? result : match.Value; 
    })); 

通過使用正則表達式,你可以一個:):]使用相同的表情,如果你已經把他們在數據庫中正確轉義匹配。在此示例中,我認爲所有的表達式是「不安全」,所以我用的是Regex.Escape呼叫

1

由於數量和表情符號可以是非常大和非常隨機的(like :) ;) >:) @}-, etc; and then new can be added anytime)我認爲,正則表達式不能用於他們全部。所以我想以更詳細的方式來解決這個問題。

  1. 負載在包含表情符號的關鍵和convert_text作爲值字典中的所有表情符號(只要確保關鍵是不能重複的,否則會出現異常)
  2. 做一個foreach每個表情關鍵和替換它在文本

聲明的字典

Dictionary<string, string> emoticons = new Dictionary<string, string>(); 

個加載表情到字典(使用的DataReader)

// declare/open the connection (depends on the current application design 

string sql = "SELECT * FROM Emoticons 
// cmd.ExecuteReader above query to get dataReader (dr) 

while(dr.Read()) 
{ 
    string key = dr.GetString(dr.GetOrdinal("Emoticons")); 

    if(!emoticons.ContainsKey(key)) 
     emoticons.Add(key, dr.GetString(dr.GetOrdinal("convert_test")); 
} 
dr.Close(); 

以上詞典可以存儲爲一個類級別的對象或作爲項目層面的全局對象,這樣你就不需要每次讀取數據庫。

與convert_text

foreach(string key in emoticons.Keys) 
    value = value.Replace(key, emoticons[key]); 

// here you will have all emoticons converted with their convert_text. 

很樂意幫忙更換所有的表情符號!如果您發現它有幫助,請記住接受答案。