简体   繁体   中英

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

I want to make a program that finds how many times a key word has been repeated (ie "the") and then store the index position in a array. At the moment, my code only store's the first time it reads "the" in the string sentence. How do you make it that it stores the index position of the first time it reads "the" and the second?

It outputs on the console:

11
0

My current code:

        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();

Second result ( 0 ) is there because of unnecessary i++ in the for loop. Because of that, you are entering the loop only once. To achieve what you want you could try code like below (please take a closer look at body of the for loop:

            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 hope it makes sense.

There are two problems that I see with your code. First, you're incrementing i twice, so it will only ever get half the items. Second, you're passing i as the second parameter to IndexOf (which represents the starting index for the search). Instead, you should be starting the search after the previous found instance by passing in the index of the last instance found plus its length.

Here's a fixed example of the for loop:

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

Also, your code could be simplified a little if you use a List<int> instead of an int[] to store the indexes, because with List you don't need to know the count ahead of time:

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM