如何过滤和删除不包含特定单词的行

本文关键字:包含特 单词 删除 何过滤 过滤 | 更新日期: 2023-09-27 17:56:52

这是现在的方法:

private void WordsFilter(List<string> newText)
{
    for (int i = 0; i < newText.Count; i++)
    {
        for (int x = 0; x < WordsList.words.Length; x++)
        {
            lineToPost = ScrollLabel._lines[i];
            if (!lineToPost.Contains(WordsList.words[x]))
            {
                newText.Remove(lineToPost);
            }
        }
    }
}

newText 是 List 和 WorldsList.words 是 string[]

我循环遍历 newText 中的行并循环遍历单词,我想以这种方式检查:

newText 中的第一行,如果此行中不存在任何单词,则遍历所有单词,删除当前行及其后的下一行。例如,在 newText 中,如果索引 0 中的行是:大家好索引 1 中的行是:创建于 12/3/2002然后删除索引 0 和索引 1

索引 2 像空格空行一样为空,因此不要将其删除。

然后索引 3

循环遍历所有单词,如果索引 3 中的行中不存在任何单词,则删除索引 3 和索引 4。

等等...

我该怎么做?

如何过滤和删除不包含特定单词的行

这是一个工作示例。我尽量不改变你的代码逻辑:

using System;
using System.Collections.Generic;
public class Program
{
    public static void Main()
    {
        List<string> list = new List<string>() {"truc", "I love toto", "next", "chocolate", "tata tata", "", "something"};
        WordsFilter(list);
    }
    private static void WordsFilter(List<string> newText)
    {
        string[] WordsList = new string[] { "toto", "tata" };
        for (int i = 0; i < newText.Count; i++)
        {
            for (int x = 0; x < WordsList.Length; x++)
            {
                if (newText[i].Contains(WordsList[x]))
                {
                    newText.RemoveAt(i);
                    if (i + 1 < newText.Count)
                        newText.RemoveAt(i);
                }
            }
        }
        // print
        foreach(var item in newText)
        {
            Console.WriteLine(item);
        }
    }
}

您应该检查循环和 LINQ foreach工作原理。