I have this function:
public static string Autocorrect(string input)
{
string output = "";
output = input.Replace("ad", "and");
return output;
}
It replace all the "ad" occurrences with and, but also to word ads -> ands, the expectation in this example is that ads should remain the same. I want to replace only the word ad, not if a word contains "ad". How can I do this?
CodePudding user response:
You can try regular expressions:
using System.Text.RegularExpressions;
...
public static string Autocorrect(string input) => string.IsNullOrEmpty(input)
? input
: Regex.Replace(input, @"\bad\b", "and");
Pattern @"\bad\b"
explained:
\b - word boundary (white space, punctuation, beginning of the string etc.)
ab - just "ab"
\b - word boundary (white space, punctuation, end of the string etc.)
CodePudding user response:
add spcace before and after ad
output = input.Replace(" ad ", "and");
//or
//output =Regex.Replace(input, @"\bad\b", "and")
If you want to be space before and after and
output = input.Replace(" ad ", " and ");
//or
//output =Regex.Replace(input, @"\bad\b", " and ")