-2

I’m trying to develop a program that analyses sentence with several words in a string.

When a word in the sentence is inputted the program should identify all the positions that this inputted word occurs in the string. So I if I had the string:

ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU BUT WHAT YOU CAN DO FOR YOUR COUNTRY

And I inputted the word "country" it should output:

The word Country is in the positions: 5, 17

I’m not really sure where I should start after creating the string

Tom
  • 16,842
  • 17
  • 45
  • 54
  • 3
    You can start by reading the [JavaDoc of the `String` class](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html) to see what it can do for you. – Tom Dec 12 '16 at 15:18
  • This is a very simple homework with numerous ways to do it. Read up `String.indexOf()`. – user3437460 Dec 12 '16 at 15:37

1 Answers1

1

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);
        }
    }
}
Fenio
  • 3,528
  • 1
  • 13
  • 27