您可以使用正则表达式执行此操作,但似乎没有必要。以下解决方案假定建议总是以空格开头(或从句子的开头开始)。如果不是这种情况,那么您将需要分享更多示例以制定规则。
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;
}