如何存储重复关键字的索引位置并将其存储在数组中?

How do you store the index position of a repeated keyword and store it in an array?

我想制作一个程序,找出一个关键字(即“the”)被重复了多少次,然后将索引位置存储在一个数组中。目前,我的代码只存储字符串句子中第一次读取“the”的时间。你如何让它存储第一次读取“the”和第二次的索引位置?

在控制台输出:

11
0

我当前的代码:

        string sentence = "John likes the snow and the winter.";
        string keyWord = "the";

        var test = sentence.Split(new char[] { ' ', '.' });
        var count = Array.FindAll(test, s => s.Equals(keyWord.Trim())).Length;

        int[] arr = new int[count];

        for (int i = 0; i < arr.Length; i++)
        {
            arr[i] = sentence.IndexOf("the", i);
            i++;
        }
        foreach (int num in arr)
        {
            Console.WriteLine(num);
        }
        
        Console.ReadLine();

第二个结果 (0) 是因为 for 循环中不必要的 i++。因此,您只进入循环一次。要实现您想要的效果,您可以尝试如下代码(请仔细查看 for 循环的主体:

            string sentence = "John likes the snow and the winter.";
            string keyWord = "the";

            var test = sentence.Split(new char[] { ' ', '.' });
            var count = Array.FindAll(test, s => s.Equals(keyWord.Trim())).Length;

            int[] arr = new int[count];

            int lastIndex = 0;
            for (int i = 0; i < arr.Length; i++)
            {
                lastIndex = sentence.IndexOf("the", lastIndex + keyWord.Length); //We are adding length of the `keyWord`, because we want to skip word we already found.
                arr[i] = lastIndex;
            }
            foreach (int num in arr)
            {
                Console.WriteLine(num);
            }
            
            Console.ReadLine();

我希望它有意义。

我发现您的代码存在两个问题。首先,您将 i 递增两次,因此它只会获得一半的项目。其次,您将 i 作为第二个参数传递给 IndexOf(表示搜索的起始索引)。相反,您应该通过传入找到的最后一个实例的索引及其长度,在上一个找到的实例之后开始搜索。

这是 for 循环的固定示例:

for (int i = 0; i < arr.Length; i++)
{
    arr[i] = sentence.IndexOf(keyword, i == 0 ? 0 : arr[i - 1] + keyword.Length);
}

此外,如果您使用 List<int> 而不是 int[] 来存储索引,您的代码可以稍微简化,因为使用 List 您不需要知道提前数:

string sentence = "John likes the snow and the winter.";
string keyWord = "the";

var indexes = new List<int>();
var index = 0;

while (true)
{
    index = sentence.IndexOf(keyWord, index);  // Find the next index of the keyword
    if (index < 0) break;                      // If we didn't find it, exit the loop
    indexes.Add(index++);                      // Otherwise, add the index to our list
}

foreach (int num in indexes)
{
    Console.WriteLine(num);
}