how to get the index for first occurence of any word from arraylist in sentence

I want to get the index of word from the sentence. But here I don't want to check for one specific word. I have list of words and I want to get index of the first occurrence of any word from the list which available in the sentence. I want the index to get the substring of the sentence, starting at the resulted index.

String sentence = "hii rahul ,nice to meet you .How are you?";
ArrayList search = new ArrayList();
search.add("are");
search.add("rahul");
search.add("meet");
for(int i=0;i<search.size();i++)
{
  if (sentence.contains(search.get(i))) {
    System.out.println("I found the keyword");
  } else {
    System.out.println("not found");
  }

I tried writing some code, but could not figure out how to get the index of the String "rahul".

Input: Sentence: hii rahul ,nice to meet you .How are you? ArrayList of searched words: ["meet","are","rahul"]

Expected output: Index is 4 (as the rahul comes first in the sentence)


You probably need to split your string into a list of words.

If you just use contains or indexOf, it may give the wrong answer. For example...

        String search = "Doctor Smith went gardening and then went to the cinema on Tuesday";
        List<String> words = Arrays.asList("then", "to", "went");

This would give the wrong answer if using indexOf because the character sequence 'to' appears within the word 'Doctor'.

This does a match on whole words (case sensitive)...

import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;

public class FindWord {

    public static void main(String[] args) {
        String search = "Doctor Smith went gardening then went to the cinema on Tuesday";
        List<String> words = Arrays.asList("then", "to", "went");

        int index = 0;
        int result = -1;
        String match = null;

        StringTokenizer tokenizer = new StringTokenizer(search, " ", true);

        while(result < 0 && tokenizer.hasMoreElements()) {
            String next = tokenizer.nextToken();

            if(words.contains(next)) {
                result = index;
                match = next;
            } else {
                index += next.length();
            }
        }

        if(match == null) {
            System.out.println("Not found.");
        } else {
            System.out.println("Found '" + match + "' at index: " + result);
        }
    }
}

Using indexOf to Find All Occurrences of a Word in a String, Using indexOf to Find All Occurrences of a Word in a String. Last modified: July 20, In the media, editors locate a particular phrase in a voluminous text. Data surveillance List<Integer> indexes = new ArrayList<Integer>();. Example – Get the index of first occurrence of a substring – Ignore Case In this example, we ignore the case of both the strings and try to find the occurrence of string str2 in string str1 . To ignore the case, we have actually converted the strings to lowercase and then applied the function indexOf().


You can use String.indexOf(String) to determine the starting position of a substring:

Integer lowestIndex = null;
for(String searchWord : search) {  
    int index = sentence.indexOf(searchWord);
    // update the result if the searchWord occurs at a lower position
    if (index >= 0 && (lowestIndex == null || lowestIndex > index)) {
            lowestIndex = index;
        }
    } 
}
if (lowestIndex == null) {
    System.out.println("None of the keywords were found");
}
else {
    System.out.printf("First keyword at %s%n", lowestIndex);
}

How to get the index of first occurrence of a substring in a String , To find the index of first occurrence of a substring in a string you can use String. indexOf() function. In this tutorial, we have examples to find the occurrence of str2 � Searches for the specified object and returns the index of its first occurrence in a one-dimensional array. IndexOf(Array, Object, Int32) Searches for the specified object in a range of elements of a one-dimensional array, and returns the index of its first occurrence. The range extends from a specified index to the end of the array.


Matcher m = Pattern.compile("(meet|are|rahul)").matcher(searchText);
if (m.find()) {
    System.out.printf("Found '%s' at position %d%n",
        m.group(), m.start());
}

If you want to start with a List:

List<String> keywords = Arrays.asList("meet","are","rahul");
String pattern = keywords.stream().collect(Collectors.joining("|", "(", ")"));

A regular expression search is slower, but one could add word boundaries \\b(meet|are|rahul) so "software" is not found. Or do a case-insensitive search.

Finding all the indexes of a whole word in a given string using java , Finding all the indexes of a whole word in a given string using java. Intent. To find all the This will give us the index of first occurrence of keyword (“be”). List< IndexWrapper> wrappers = new ArrayList<IndexWrapper>();. In this Java tutorial, you will learn How to Find Maximum Occurrence of Words from given Text File?. Here is a logic for getting top element: Create a class CrunchifyComparable that can store the String value of the word and the number of occurrences it appears.


You can use String.indexOf method. But be aware that indexing starts from 0, so in your example the output will be 4.

String indexOf() Method in Java with EXAMPLE, cha − a character. Return Value. This Java method returns the index within this string of the first occurrence of the specified character. It returns -1� index of 7, in "or" index of 122, in "fortune" index of 130, in "Or index of 221, in "more" index of 438, in "For" In mathematical terms, the algorithm has a Big-O notation of O(m*(n-m)), where m is the length of the word and n is the length of the text string. This approach may be appropriate for haystack text strings of a few thousand


Something like this perhaps:

int firstIndex = Integer.MAX_VALUE;
for(String word : search) {
  int foundIndex = sentence.indexOf(word);
  if(foundIndex != -1 && foundIndex < firstIndex){
    firstIndex = foundIndex;
  }
}

if(firstIndex != Integer.MAX_VALUE){
  System.out.println("Found index is: " + firstIndex);
} else{
  System.out.println("None of the words were found in the sentence.");
}

If the word is not found .indexOf will return -1. If it is found, we save the lowest in the firstIndex-variable.

Try it online.

Java String indexOf() Method, fromIndex, An int value, representing the index position to start the search from Find the first occurrence of the letter "e" in a string, starting the search at� Say we want to extract the first sentence from the example String. This is quite easy to do using split: String[] sentences = text.split("\\."); Since the split method accepts a regex we had to escape the period character. Now the result is an array of 2 sentences. We can use the first sentence (or iterate through the whole array):


Replace a character at a specific index in a String in Java , Given a String, the task is to replace a character at a specific index in this string in Java. Examples: Input: String = "Geeks Gor Geeks", index = 6, ch = 'F' Output: " Geeks For Get hold of all the important DSA concepts with the DSA Self Paced Course at a last_page How to sort an ArrayList in Descending Order in Java. int indexOf(int ch, int fromIndex): It returns the index of first occurrence of character ch in the given string after the specified index “fromIndex”. For example, if the indexOf() method is called like this str.indexOf(‘A’, 20) then it would start looking for the character ‘A’ in string str after the index 20.


Find the starting indices of the substrings in string (S) which is made , You are given a string S, and a list of words L i.e array/vector of strings Find the starting indices of the substrings in string S, which contains all the Recommended: Please try your approach on {IDE} first, before moving on to the solution. which stores all words of List L corresponding to their occurrences inside list L. index() is an inbuilt function in Python, which searches for given element from start of the list and returns the lowest index where the element appears. Syntax : list_name.index(element, start, end)


Java.util.ArrayList.indexOf() Method, o − The element to search for. Return Value. This method returns the index of the first occurrence of the specified element in this list, or -1 if this list does not� Recommended: Please try your approach on first, before moving on to the solution. The idea is to create a count array of size 256. Traverse input string and for every character increment its count.