Как найти определенные слова в строке и вывести их вместе с их индексами?

Рейтинг: 0Ответов: 3Опубликовано: 01.03.2023

Нужно сделать следующее: в тексте найти такие слова как "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Принят

Делаем список искомых слов и итерируем по нему. Каждое слово ищем в цикле внутри строки, пока не найдем все вхождения начиная с индекса 0. Их выводим. После нахождения очередного вхождения передвигаем стартовый индекс поиска на длину найденного слова. Если больше вхождений нет, выходим из цикла и переходим к поиску следующего слова.

list = ["of", "in", "new", "from", "this", "rail", "spliter"]
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.";
list.forEach(word => {
  let pos = 0
  while (true) {
    pos = m.indexOf(word, pos)
    if (pos < 0) break;
    else {
      console.log(`${word} -> ${pos}`)
      pos += word.length
    }
  }
})

Второй вариант - итерируем по строке, на каждом шаге сверяем, начинается ли подстрока с одного из искомых слов.

list = ["of", "in", "new", "from", "this", "rail", "spliter"]
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.";
for (i = 0; i < m.length; i++) {
  list.forEach(word => {
    if (m.startsWith(word, i)) console.log(`${word} -> ${i}`)
  })
}

▲ 0

Можно собрать все индексы вхождения слов и вывести их.

const text = '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.";';
const letters = ['of', "in", "new", "from", "this", "rail", "spliter"];

function getIndexs(txt, words) {
  const accum = {};
  words.forEach(it => accum[it] = []); // Создадим начальное состояние
  return words.reduce((acc, item) => {
    let idx;
    while (true) {
      idx = txt.indexOf(item, idx);
      if (idx > -1) {
        acc[item].push(idx); // Собираем вхождения
        idx += item.length;
      } else break;
    }
    return acc;
  }, accum);
}

const result = getIndexs(text, letters);
for (let i in result) {
  console.log(`Слово '${i}' найдено ${result[i].length} раз. Позиции`, '->', result[i].join(', ')); // выводим результат
}

▲ 0

в тексте найти такие слова как "of" "in" "new" "from" "this" "rail" "spliter", вывести их в консоль и индексы их вхождений

Предложу такой вариант...

const txt = '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.'
test(txt)

function test(txt) {
  const w = ["of", "in", "new", "from", "this", "rail", "spliter"]
  const r = w.map(v => new RegExp('\\b' + v + '\\b'))
  const p = Array(w.length).fill(0)
  const o = {}
  do {
    w.forEach((v, i) => {
      if (p[i] === -1) return
      const j = txt.indexOf(v, p[i])
      if (j === -1) {
        p[i] = -1
        return
      }
      p[i] = j + 1
      const s = txt.substring(j - 1, j + v.length)
      if (!r[i].test(s)) return
      o[v] ? o[v].push(j) : o[v] = [j]
    })
  } while (p.some(v => v != -1))
  w.forEach(k => {
    if (!o[k]) return
    o[k].forEach(i => console.log('%s -> %s', k, i))
  })
}