Trying to add a count to a variable everytime a string matches an element in my string array

Viewed 106

So, I have a string array. For instance, [test, exam, quiz] which we will call cat to prevent misunderstanding. I also have a string. For instance, String school = "We have a test and a quiz next week". I am checking the string school to see if it contains/matches the string array [test, exam, quiz]. However, I want to keep track of how many matches are occurring in a count variable. I haven't been able to figure out how to add one to the count for each match. For instance, based on the scenario constructed, there should be two matches of the three in the string array.

Here is my code:

int i = 0;

for (String s : cat) {
    if (school.contains(s)) {
        match = true;
        i++;
        break;
    }
}

The output for this code only gives 1, even though the string school contains test and quiz. I want it to give two.

Your help would be much appreciated.

5 Answers

All you have to do is:

  1. Split given school into separate words;
  2. Using filter() to filter out required words;
  3. Count elements in the stream.
String school = "We have a test and a quiz next week test";
String[] cat = { "test", "exam", "quiz" };
Set<String> words = Arrays.stream(cat).collect(Collectors.toSet());
long count = Arrays.stream(school.split("\\s+"))
                   .filter(words::contains)
                   .count();

One approach uses an alternation of search terms along with a formal regex pattern matcher:

String[] cat = new String[] {"test", "exam", "quiz"};
StringBuilder regex = new StringBuilder("\\b(?:");
for (int i=0; i < cat.length; ++i) {
    if (i > 0) regex.append("|");
    regex.append(cat[i]);
}
regex.append(")\\b");

String school = "We have a test and a quiz next week";
Pattern r = Pattern.compile(regex.toString());
Matcher m = r.matcher(school);
int count = 0;

while (m.find()) {
    ++count;
}

System.out.println("found " + count + " matches.");  // found 2 matches.

To be clear here, the regex pattern we are using against the input sentence is:

\b(?:test|exam|quiz)\b

We iterate over the input sentence, and increment the counter by one for each time we hit a keyword.

break will stop the for loop after the first match. That's why you get i = 1;

int i = 0;
for (String s: cat) {
  if (school.contains(s)) {
      match=true;
      i++;
      break; // This break will stop the for loop iteration after the first match.
    }
}

To match with your both requirements you could modify your code to below.

String school = "We have a test and a quiz next week";
String[] cat = {"test", "exam", "quiz"};
int i = 0;
boolean match = false;
for (String s : cat) {
  if (school.contains(s)) {
     match = true;
     i++;
  }
}
System.out.println(match ? "found " + i + " matches." : "not found any match");

But there is an issue in this code as incase of more than one match for same text it will still count as 1 match. Example assume there are two test in school String, you will still get count as 1.

The result is 1 because you have added a break statement inside the if condition which is making it go out of the loop whenever the first match is found, instead you should write like this

int i=0;
   for (String s: cat){
      if(school.contains(s)){
         match=true;
         i++;
        }
      }

You could use a Hastable in java: (If the input sentence happens to have a keyword more than once, then your String#contains logic will still only count one match)

import java.util.Hashtable;
public class Main
{
    public static void main(String[] args) {
    
    String school = "We have a test and a quiz next week";
    String cat[] = new String[]{"test", "exam", "quiz"};
    Hashtable<String, Integer> my_dict = new Hashtable<String, Integer>();
    int count=0; // variable should be named such that it is understandable the purpose of it
    for (String s: cat){
      if(school.contains(s)){
         if(!my_dict.containsKey(s)){
             my_dict.put(s, 1);
             count++;
         }
         //else{} //don't need else in your case
        }
      }
      System.out.println( "Occurance: " + count );
    }
}

If you need mutlitple counts of the same string word in a sentence, then just remove the Hashtable and also the condition for the Hashtable as below:

 int count=0; // variable should be named such that it is understandable the purpose of it
    for (String s: cat){
      if(school.contains(s)){
             count++;
        }
      }
System.out.println( "Occurance: " + count );
Related