I have list and text file and I want:
- Find all list items that are also in string (matched words) and store them in list or array
- Replace all the found matched words with "Names"
- Count the matched words
Code:
string[] Names = new string[] { "SNOW","Jhon Snow","ADEMS","RONALDO",
"AABY", "AADLAND", "ANGE", "GEEN", "KHA", "AN", "ANG", "EE", "GEE", "HA", "HAN", "KHAN",
"LA", "LAN", "LAND", "NG", "SA", "SAN", "SANG", "LAN","HAN", "LAN", "SANG", "SANG",
"Sangeen Khan"};
string Text = "I am Sangeen Khan and i am friend AABY. Jhon is friend of AABY.
AADLAND is good boy and he never speak lie. AABY is also good. SANGEEN KHAN is my name.";
List<string> matchedWords = Names.Where(Text.Contains).ToList();
matchedWords.ForEach(w => Text = Regex.Replace(Text, "\\b" + w + "\\b",
"Names", RegexOptions.IgnoreCase));
int numMatchedWords = matchedWords.Count;
Console.WriteLine($"Matched Words: {string.Join(",", matchedWords.ToArray())}");
Console.WriteLine($"Count: {numMatchedWords}");
Console.WriteLine($"Replaced Text: {Text}");
Output:
Matched Words: AABY, AADLAND, ANGE, GEEN, KHA, AN, ANG, EE, GEE, HA, HAN, KHAN, LA, LAN, LAND, NG, SA, SAN, SANG, LAN, HAN, LAN, SANG, SANG, Sangeen Khan
Replaced Text:I am Sangeen Names and i am friend Names. Jhon is friend of Names. Names is good boy and he never speak lie. Names is also good. SANGEEN Names is my name.
Count: 25
Problems: the code find the "Matched Words" and Number of Replacement (Count) incorrect. However, the replacement is corrected after reading String compare C# - whole word match
My desired output would be:
Matched Words: Sangeen Khan, AABY, KHAN, AADLAND.
Replaced Text: I am Names and i am friend Names. jhon is friend of Names. Names is good boy and he never speak lie. Names is also good. Names KHAN is my name.
Count: 7