Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Auto correct the query before sending it to your search engine

Auto correct a query before sending it to your search engine

Read my blog here

Powered by ReSharper image

public string AutoCorrect(string query)
if (query.Length < 5)
return query;
SpellCheckClient spellCheckClient = new SpellCheckClient(new ApiKeyServiceClientCredentials("Your_BING_SpellCheck_Key_Here"));
HttpOperationResponse<SpellCheckModel> result = spellCheckClient.SpellCheckerWithHttpMessagesAsync(text: query, mode: "spell", setLang: ContentLanguage.PreferredCulture.TwoLetterISOLanguageName).Result;
IList<SpellingFlaggedToken> tokens = result.Body.FlaggedTokens;
if (tokens.Count == 0)
return query;
string autoCorrect = query;
int diff = 0;
foreach (SpellingFlaggedToken problemToken in tokens)
int offset = problemToken.Offset;
int originalTokenLength = problemToken.Token.Length;
SpellingTokenSuggestion suggestionToken = problemToken.Suggestions[0];
if (suggestionToken.Score < .5)
string suggestion = suggestionToken.Suggestion;
int lengthDiff = suggestion.Length - originalTokenLength;
autoCorrect = autoCorrect.Substring(0, offset + diff) + suggestion + autoCorrect.Substring(offset + diff + originalTokenLength);
diff += lengthDiff;
return autoCorrect;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.