-3

Given a particular String and a particular word that appears in that String, how can I calculate the number of words that preceded that word?

For instance, given the sentence "I live in a red house on the farm" and the word "red", how can I determine how many words came before the word? I'd like to create a function that takes the original String and the target word as parameters and prints a statement like:

There are 4 words before the word "red"

Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183
  • Possible duplicate of [Java: method to get position of a match in a String?](https://stackoverflow.com/questions/2615749/java-method-to-get-position-of-a-match-in-a-string) – Ulad Apr 15 '19 at 18:09
  • Try This: `String str = "I live in a red house on the farm"; String[] array = str.split(" "); int i = 0; for(String x:array){ if (!x.equals("red")){ i++; }else{ break; } } System.out.println("There are " + i + " words before red"); } }` – preciousbetine Apr 15 '19 at 18:22
  • Ideally, this should be handled by a natural language processing library. – wp78de Apr 15 '19 at 23:53

2 Answers2

0

Just find the index of the specified word and use the substring method. Then split that substring by space to get array of words:

 String str = "I live in a red house on the farm";
 int count = str.substring(0, str.indexOf("red")).split(" ").length;  // 4
Ruslan
  • 6,090
  • 1
  • 21
  • 36
-1

Usually you can do this by a find, search or indexOf function:

try that: https://www.geeksforgeeks.org/searching-for-character-and-substring-in-a-string/

// Java program to illustrate to find a character 
// in the string. 
import java.io.*; 

class GFG 
{ 
  public static void main (String[] args) 
  { 
    // This is a string in which a character 
    // to be searched. 
    String str = "GeeksforGeeks is a computer science portal"; 

    // Returns index of first occurrence of character. 
    int firstIndex = str.indexOf('s'); 
    System.out.println("First occurrence of char 's'" + 
                       " is found at : " + firstIndex); 

    // Returns index of last occurrence specified character. 
    int lastIndex = str.lastIndexOf('s'); 
    System.out.println("Last occurrence of char 's' is" + 
                       " found at : " + lastIndex); 

    // Index of the first occurrence of specified char 
    // after the specified index if found. 
    int first_in = str.indexOf('s', 10); 
    System.out.println("First occurrence of char 's'" + 
                       " after index 10 : " + first_in); 

    int last_in = str.lastIndexOf('s', 20); 
    System.out.println("Last occurrence of char 's'" + 
                     " after index 20 is : " + last_in); 

    // gives ASCII value of character at location 20 
    int char_at = str.charAt(20); 
    System.out.println("Character at location 20: " + 
                                             char_at); 

    // throws StringIndexOutOfBoundsException 
    // char_at = str.charAt(50); 
  } 
}