C#中的字符串子集匹配

时间:2012-06-15 11:20:48

标签: c# regex string

好的,我有一个自动完成/字符串匹配问题需要解决。我有一个用户输入的表达式字符串到文本框中,例如

enter image description here

更详细信息:

表达式文本框有字符串

  

“买一些铝”

和客户端有一个服务器在填充列表框的模糊匹配后给出的建议列表

  

所有麸皮,杏仁,Alphabetti Spaghetti

现在在GUI上我有一个很好的intellisense样式自动完成,但我需要连接“TAB”动作来执行完整。因此,如果用户按下TAB并且“All Bran”是最高建议,则字符串变为

  

“买一些全麸皮”

e.g。字符串“Al”代替顶部匹配“All Bran”

这不仅仅是对表达式进行简单的字符串拆分以匹配建议,因为表达式文本可能是这个

  

“买一些所有的麸皮和铝”

有建议

  

Alphabetti Spaghetti

在这种情况下,我希望最终的Al被顶部匹配替换,因此结果变为

  

“买一些全麸皮和Alphabetti Spaghetti”

我想知道如何简单地在C#(只是C#字符串操作,而不是GUI代码)中执行此操作,而无需返回服务器并要求进行替换。

3 个答案:

答案 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;
}

答案 1 :(得分:0)

使用string.Join(" and ", suggestions)创建替换字符串,然后string.Replace()进行替换。

答案 2 :(得分:0)

您可以在数组中添加列表框项目,并在遍历数组时,一旦找到匹配项,断开循环并退出并显示输出。