Вот метод, который делает это.Идет по ключевому слову, сравнивая, игнорируя регистр.Если ключевое слово найдено, проверяется, есть ли пробел до и / или после, и добавляется его.
public static string AddSpacesAroundWords(string text, List<string> words)
{
foreach(string word in words) {
int index = 0;
while(index < text.Length) {
index = text.IndexOf(word, index, StringComparison.CurrentCultureIgnoreCase);
if(index == -1) {
// no occurrence of this word anymore
break;
}
// check if there is a space at the beginning of the word
if(index > 0 && text[index - 1] != ' ') {
text = text.Insert(index++ - 1, " ");
}
// check if there is a space at the end of the word
if(index + word.Length < text.Length && text[index + word.Length] != ' ') {
text = text.Insert(index++ + word.Length, " ");
}
index += word.Length;
}
}
return text;
}
Использование:
string original = "Today the auto industry is booming. Automated machines are big part of it and it's working great. They are doing very big autonomous work.";
var words = new List<string> { "auto", "work", "the" };
string result = AddSpacesAroundWords(original, words);
// result is now "Today the auto industry is booming. Auto mated machines are big part of it and it's work ing great. The y are doing very big auto nomous work ."