[英]How do you store the index position of a repeated keyword and store it in an array?
我想制作一個程序,找出一個關鍵字被重復了多少次(即“the”),然后將索引 position 存儲在一個數組中。 目前,我的代碼只存儲字符串句子中第一次讀取“the”的時間。 你如何讓它存儲第一次讀取“the”和第二次的索引 position?
它在控制台輸出:
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.