How do I search for exact word in a String array which contain sentences(JAVA)

Radon :

I have a String array containing n number of elements desired by user.

Suppose if there are 3 String elements:

Hey,
Hello there,
Hell no

And I want to search for the word Hell.

The program should give out the third sentence only not the second sentence since hello has the word hell in it.

Another example - elements are:

10
50
110

If I search for 10 the output should be the first sentence and not third one (Since 110 contains 10).

I have created a linear search array for String but I don't get how to implement it on words in sentences.

Help would be appreciated.Thank you.

Nicholas K :

The equals method is a better fit for your requirement :

String strArray[] = { "Hey", "Hello there", "Hell no" };
String inputStr = "Hell";

for (int i = 0; i < strArray.length; i++) {
    String[] contents = strArray[i].split(" ");
    for (int j = 0; j < contents.length; j++) {
        if (inputStr.equals(contents[j])) {
            System.out.println(strArray[i]);
        }
    }
}

Here, we iterate over the initial array, split each word and then loop over the resulting array to check if there is a match.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=159305&siteId=1