Please, read the JavaDoc provided in the comment.
Basically when you have String
you can perform split
operation by calling split(" ")
method. This will split whole string into an array String[]
Then you can just iterate through the array and print word's position.
Remember: Operations on string can be performed in various ways
Working example:
public static void main(String[] args) {
String wholeString = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU BUT WHAT YOU CAN DO FOR YOUR COUNTRY";
String[] justWords = wholeString.split(" ");
String searchString = "COUNTRY";
for (int i = 0; i < justWords.length; i++) {
if (justWords[i].equals(searchString)) {
System.out.println("The word " + searchString + " is in the position: " + i);
}
}
}
Keep in mind that I am counting since 0 so the position for word COUNTRY will be in 4 and 16 instead of 5 and 17, but you should be able to adjust it to your requirements
Output:
The word COUNTRY is in the position: 4
The word COUNTRY is in the position: 16
JavaDoc
Additional Example where String you search for is an user input.
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter word you are looking for");
String searchString = br.readLine();
String wholeString = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU BUT WHAT YOU CAN DO FOR YOUR COUNTRY";
String[] justWords = wholeString.split(" ");
for (int i = 0; i < justWords.length; i++) {
if (justWords[i].equals(searchString)) {
System.out.println("The word " + searchString + " is in the possition: " + i);
}
}
}