你需要做的是:在文本中找到“of”“in”“new”“from”“this”“rail”“spliter”等词,将它们输出到控制台以及它们出现的索引,对于例如,程序的结果应该是这样的:
of -> 16
of -> 60
...
我写了这段代码,但它不起作用:
let m = "The nationalism of Hamilton was undemocratic. The democracy of Jefferson was, in the beginning, provincial. The historic mission of uniting nationalism and democracy was in the course of time given to new leaders from a region beyond the mountains, peopled by men and women from all sections and free from those state traditions which ran back to the early days of colonization. The voice of the democratic nationalism nourished in the West was heard when Clay of Kentucky advocated his American system of protection for industries; when Jackson of Tennessee condemned nullification in a ringing proclamation that has taken its place among the great American state papers; and when Lincoln of Illinois, in a fateful hour, called upon a bewildered people to meet the supreme test whether this was a nation destined to survive or to perish. And it will be remembered that Lincolns party chose for its banner that earlier device--Republican--which Jefferson had made a sign of power. The \"rail splitter\" from Illinois united the nationalism of Hamilton with the democracy of Jefferson, and his appeal was clothed in the simple language of the people, not in the sonorous rhetoric which Webster learned in the schools.";
let tmp = "";
let i, j;
for(i = 0; i < m.length; i++) {
if((m.charAt(i) == "o") || (m.charAt(i) == "i") || (m.charAt(i) == "n") || (m.charAt(i) == "f") || (m.charAt(i) == "t") || (m.charAt(i) == "r") || (m.charAt(i) == "s")) {
index = i; //в нем храним индекс первой буквы в потенциально подходящем слове
for (j = i; m.charAt(j) != " "; j++) {
tmp = tmp + m.charAt(j);
}
if ((tmp == "of") || (tmp == "in") || (tmp == "new") || (tmp == "from") || (tmp == "this") || (tmp == "rail") || (tmp == "spliter")) {
console.log(tmp, "- > ", index);
}
}
tmp = "";
}
请帮我解决这个问题
我们制作一个搜索词列表并对其进行迭代。我们在字符串内循环搜索每个单词,直到找到从索引 0 开始的所有匹配项。我们显示它们。找到下一个出现后,我们将搜索的起始索引移动找到的单词的长度。如果不再出现,则退出循环并继续搜索下一个单词。
第二种选择是遍历字符串,在每一步中我们检查子字符串是否以搜索到的单词之一开头。
您可以收集单词出现的所有索引并显示它们。
我会提供这个选项...