2012-06-15 34 views
1

好吧我有一個自動完成/字符串匹配問題需要解決。我有一個用戶輸入到文本框中的表達式字符串,例如,C中的字符串子集合匹配#

enter image description here

更多細節:

表達文本有串

「買一些鋁」

和客戶端具有由服務器給出的建議列表經過模糊匹配後填充列表框

所有麩,杏仁,Alphabetti麪條

現在在GUI上我有一個很好的智能感知風格自動完成的,但我需要的電纜鋪設「TAB」的行動來執行完成。因此,如果用戶按下TAB和「全麥維」被頂建議,字符串變成

「買一些全麥維」

例如字符串「鋁」代替頂級比賽「全麥維」

這是不是在表達一個簡單的字符串分割更相匹配的建議,作爲表達的文字可能是這個

「買一些全麥維和Al」

與建議

Alphabetti麪條

在這種情況下,我認爲,最終的Al與頂級比賽被替換,以便結果變成

「買一些全麥維和Alphabetti意粉」

我不知道如何只需在C#(只是C#字符串操作,而不是GUI代碼)中執行此操作,而無需返回到服務器並要求進行替換。

+0

不知道我理解的問題 - 你說的服務器已經返回模糊匹配列表 - 所以你已經在客戶端的數據,爲什麼你需要再次查看數據庫嗎? – Charleh

+0

它是什麼類型的應用程序? Web,桌面? –

+0

@Charleh我添加了一張圖片來澄清。基本上在客戶端,我有當前未完成的表達式字符串,建議列表,但在按下標籤時,我需要在表達式中插入頂部的建議。 Jakub - gui技術是Silverlight的,我只是對C#代碼感興趣,但是它可以做字符串替換。 –

回答

0

使用string.Join(" and ", suggestions)創建您的替換字符串,然後string.Replace()做替換。

+0

不確定這會起作用 - 如果用戶輸入了一半的建議,我需要用最頂級的建議替換部分匹配 –

0

您可以在數組中添加列表框項,並在遍歷數組時,一旦找到匹配項,就打破循環並退出並顯示輸出。

1

你可以用正則表達式做這件事,但似乎沒有必要。以下解決方案假定建議始終以空格開頭(或在句首開始)。如果情況並非如此,那麼您將需要分享更多示例來降低規則。

string sentence = "Buy some Al"; 
string selection = "All Bran"; 
Console.WriteLine(AutoComplete(sentence, selection)); 

sentence = "Al"; 
Console.WriteLine(AutoComplete(sentence, selection)); 

sentence = "Buy some All Bran and Al"; 
selection = "Alphabetti Spaghetti"; 
Console.WriteLine(AutoComplete(sentence, selection)); 

這裏是AutoComplete方法:

public string AutoComplete(string sentence, string selection) 
{ 
    if (String.IsNullOrWhiteSpace(sentence)) 
    { 
     throw new ArgumentException("sentence"); 
    } 
    if (String.IsNullOrWhiteSpace(selection)) 
    { 
     // alternately, we could return the original sentence 
     throw new ArgumentException("selection"); 
    } 

    // TrimEnd might not be needed depending on how your UI/suggestion works 
    // but in case the user can add a space at the end, and still have suggestions listed 
    // you would want to get the last index of a space prior to any trailing spaces 
    int index = sentence.TrimEnd().LastIndexOf(' '); 
    if (index == -1) 
    { 
     return selection; 
    } 
    return sentence.Substring(0, index + 1) + selection; 
}