Найти и исправить слова в тексте - C#
Формулировка задачи:
Дан текст и список слов. Найти в тексте все слова, каждое из которых отличается от некоторого слова из списка одной буквой, и исправить такие слова на слова из списка.
Решение задачи: «Найти и исправить слова в тексте»
textual
Листинг программы
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Linq;
namespace ConsoleApplication207
{
internal class Program
{
private static void Main(string[] args)
{
var text = "маму мыла раму, а папу мыл аккордеон.";
var templates = new List<Template>()
{
new Template("мама"),
new Template("папа")
};
CheckText(ref text, templates);
Console.WriteLine(text);
Console.ReadLine();
}
private static void CheckText(ref string text, List<Template> templates)
{
foreach(Match m in Regex.Matches(text.ToLower(), @"\w+"))//получаем список слов
{
var word = m.Value;
foreach(var template in templates)//перебираем шаблоны
if(template.GetDistance(word) == 1)//если одно отличие от шаблона
{
//делаем замену слова на шаблон
text = text.Substring(0, m.Index) + template.Word + text.Substring(m.Index + m.Length);
break;
}
}
}
}
class Template
{
public string Word { get; set; }
public Template(string template)
{
this.Word = template;
}
public int GetDistance(string word)
{
if (word.Length != Word.Length)
return 100;
var dist = 0;
for (int i = 0; i < word.Length; i++)
if (Word[i] != word[i])
dist++;
return dist;
}
}
}