Home > Software engineering >  How to Find the word that comes after a specified word in java String
How to Find the word that comes after a specified word in java String

Time:06-09

My program has a String inputted Eg. hello i am john who are you oh so i see you are also john i am happy

my program then has a keyword inputted Eg. i (the program doesn't like capitals or punctuation yet)

then it reads the initial String and finds all the times it mentions the keyword the word after the keyword, Eg. i am, i see, i am.

with this is finds the most common occurrence and outputs that second word as the new keyword and repeats. this will produce i am john/happy (when it comes to an equal occurrence of a second word it stops (it is meant to))

What i want to know is how i find the word after the keyword.

package main;

import java.util.Scanner;

public class DeepWriterMain {

    public static void main(String[] args) {
    
        String next;
        Scanner scanner = new Scanner(System.in);
        System.out.println("text:");
        String input = scanner.nextLine();
        System.out.println("starting word:");
        String start = scanner.nextLine();
        input.toLowerCase();
        start.toLowerCase();
        if (input.contains(start)) {
             System.out.println("Loading... (this is where i find the most used word after the 'start' variable)");
             next = input.substring(5, 8);
             System.out.println(next);
         }else {
             System.out.println("System has run into a problem");
         
         }
    }

}

CodePudding user response:

If you use split to split all your words into an array, you can iterate through the array looking for the keyword, and if it is not the last in the array, you can print the next word

String arr [] = line.split(" ");
for (int i = 0; i < arr.length -1; i  ) {
    if (arr[i].equalsIgnoreCase(keyword)) {
       sop(arr[i]   " " arr[i   1]);
    
} 
  • if it is not the last in the array, iterate only to length - 1

CodePudding user response:

The String class includes a method called public int indexOf(String str). You could use this as follows:

int nIndex = input.indexOf(start)   start.length()

You then only need to check if nIndex == -1 in the case that start is not in the input string. Otherwise, it gets you the position of the first character of the word that follows. Using the same indexOf method to find the next space provides the end index.

This would allow you to avoid a linear search through the input, although the indexOf method probably does one anyway.

  • Related