0

So I want to search for a argument a user inputs such as "Hello there" without looking for "Hello" and "There" its self.

String[] words = text.split("\\s+");        
    for (int i = 0; i < words.length; i++){
         if (searchString.contains(words[i])){
             counter++;
         }
    }

Heres the code Im basically trying to count how many times a string appears in txt file.

  • Huh? "Hello there" is **two** words. Why are you `split`ing the text? `text.contains(searchString)`? Did you want to count the number of times `searchString` appears in `text`? – Elliott Frisch Mar 24 '18 at 23:27
  • how does your text file look like? please show an example input and expected output. – Ousmane D. Mar 24 '18 at 23:31
  • yea I want to count the number of times the "Hello there" is placed together not individually through the text. Im splitting from white spaces, and yes I want t count how many times searchString shows up. – Ismail Ghelle Mar 24 '18 at 23:31
  • this is this the expected out put (java TextSearch "drops of blood" input.txt) output: the snow, she pricked her finger, and there fell from it three drops of blood on the snow. And when she saw how bright and red it looked, she Total matches: 1 – Ismail Ghelle Mar 24 '18 at 23:34
  • probably duplicate of https://stackoverflow.com/questions/7378451/java-regex-match-count – senseiwu Mar 24 '18 at 23:34

2 Answers2

0

I'd probably use Pattern and Matcher.

  Pattern p = Pattern.compile("Hello there");
  Matcher m = p.matcher(text);
  int counter = 0;
  while (m.find()) {
      counter++;
      System.out.println("found hello there!");
  }

Counter will reflect the number of matches found in the text.

(Answer edited to reflect clarification in comments)

arcsin
  • 11
  • 4
0

use Pattern, Matcher and autoincrement integer

public static int stringCounter(String input, String toSearch)
{
     int counter = 0;
     Pattern pattern = Pattern.compile(toSearch);
     Matcher  matcher = pattern.matcher(input);
     while (matcher.find()) counter++;
     return counter;
}
Héctor M.
  • 2,302
  • 4
  • 17
  • 35