In this article I’ll explain how to implement word completion feature. This feature is very popular and very useful and comes with most good text editors (Don’t count the MS Notepad). You may also want to implement that feature in your application. If you do then this article will help you in getting the simple logic behind this feature.
This article covers the following:
- About Word Completion
- Understanding The Logic
- Implementing The Logic
- Other Variants
About Word Completion
If you are familiar with Notepad++ then you must have used this feature. In word completion we type a few characters of the beginning of the word and when we press "Cntrl + Enter" our word is completed automatically. This is the only thing that word completion deals with. Don’t mix word completion with intelli sense of Visual Studio or Code Snippets, they are entirely different. So now we know what word completion does.
Understanding The Logic
To create this module we can use the following logic (not optimized):
- Create a list of keywords that we want to be completed.
- Monitor the user keystrokes to create a word that the user is typing into the text box.
- The moment the user presses space (or any other punctuation you want to set) do the following:
- Search the word in the keyword list
- If a match is found in the keyword list then replace the text entered by the user with the keyword we found during the search.
- Move the input cursor to end of the text.
- If search results do no match then reset the word to empty.
That’s how our word completion will work. Let’s write a pseudo code for it.
- Create KEYWORD List and add all words in it.
- On Key Press in Text Area do
- word += character
- for each item in KEYWORD do
- if item.startsWith(word) then
- textBox.text = previous textbox text + item
Implementing The Logic
public partial class MainPage : PhoneApplicationPage
string word = “”;
List<string> keywordList = new List<string>();
private void txtArea_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
if (e.Key == System.Windows.Input.Key.Space)
foreach (var item in keywordList)
string temp = txtArea.Text;
txtArea.Text = temp.Substring(0, temp.Length – word.Length-1) + item + ” “;
word = “”;
word = “”;
else if (!char.IsControl(char.ConvertFromUtf32(e.PlatformKeyCode),0))
word += char.ConvertFromUtf32(e.PlatformKeyCode);
- In this version I’m not considering the situation of multiple matches. But for real use it is a must.
- The search in the list is a costly operation so I’ll recommend you use a hashing technique for the search.
- To make it more useful you can generate a keyword list dynamically and update it with all the new words entered.