Вставьте пробел до и после определенных ключевых слов, если они найдены в строке с использованием C # - PullRequest
0 голосов
/ 01 марта 2019

У меня есть тупая строка

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.

Я хочу дать словарь ключевых слов в виде List<string>.

Тогда я хочу найти эти ключевые слова в моем тексте.Если ключевое слово найдено, проверьте, есть ли место до и после.Если да, ничего не делай.Если не содержит, то добавьте пробел до или после.Таким образом, ключевое слово может быть частью слова в начале, середине или конце.Поэтому в основном делайте ключевые слова отдельными словами в тексте.

Примеры ключевых слов: auto, work, the

Для моего текста

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.

результат должен быть:

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 .

Ответы [ 2 ]

0 голосов
/ 02 марта 2019

Это просто переделка / вариант ответа ГрегаМохорко, за который я проголосовал:

private void Form1_Load(object sender, EventArgs e)
{
    tbKeywords.Text = "auto, work, the";
    textBox1.Text = "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.";
}

private void button1_Click(object sender, EventArgs e)
{
    textBox2.Text = AddSpaceAroundWords(textBox1.Text, tbKeywords.Text);        
}

private string AddSpaceAroundWords(string sentence, string CommaSeparatedKeyWords)
{
    int index;
    string keyword;
    foreach (string key in CommaSeparatedKeyWords.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
    {
        index = 0;
        keyword = key.Trim();       
        while ((index = sentence.IndexOf(keyword, index, StringComparison.InvariantCultureIgnoreCase)) != -1)
        {
            if ((index > 0) && (sentence[index - 1] != ' '))
            {
                sentence = sentence.Insert(index++, " ");
            }
            if (((index + keyword.Length) < sentence.Length) && (sentence[index + keyword.Length] != ' ')) {
                sentence = sentence.Insert(index++ + keyword.Length, " ");
            }
            index += keyword.Length;
        }
    }
    return sentence;
}
0 голосов
/ 01 марта 2019

Вот метод, который делает это.Идет по ключевому слову, сравнивая, игнорируя регистр.Если ключевое слово найдено, проверяется, есть ли пробел до и / или после, и добавляется его.

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 ."
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...