If you only want to check if a String contains a Word then you can use the .contains("");
method provided by String
String word = "COUNTRY";
String sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOU COUNTRY";
System.out.println(sentence.contains(word));
//will return true;
If you want to find all the words inside the sentence then use this:
String word = "COUNTRY";
String sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOU COUNTRY";
if (sentence.contains(word)) {
String[] sentenceWords = sentence.split(" ");
for (String wordInSentence : sentenceWords) {
if (wordInSentence.equals(word)) {
System.out.println(wordInSentence);
}
}
}
Or if you want to know the exact location of a specific word, then try this:
String word = "COUNTRY";
String sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOU COUNTRY";
if (sentence.contains(word)) {
String[] sentenceWords = sentence.split(" ");
for (int i = 0; i < sentenceWords.length; i++) {
if (sentenceWords[i].equals(word)) {
System.out.println(word + " is located as the: " + i + "th string");
}
}
}
Note: See that i use .equals();
on String objects see this post for more information!
EDIT:
To ignore the case you can use String.equalsIgnoreCase()
instead of String.equals()