Thursday, June 7, 2012

Counting words in a string

I had a question this morning from a student, asking when using a pattern matcher, if he could count the number of "hi" words in a string that didn't start with an "x".

Of course you can!


import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CountOccurences {
  
  // Our test string has 5 occurences.
  private static String input_string = "hi lo and xhi xhi hihi loxhihixhihi";
  
  public static void main(String args[]) {
    int count = 0;
    Pattern pattern = Pattern.compile("[^x]*hi");
    Matcher matcher = pattern.matcher(input_string);
    
    while (matcher.find()) {
      count++;
    }
    
    System.out.println("The final count is " + count);
  } 
}
  
Now I'll leave it as an exercise for you to go read up on Regular Expressions...

No comments:

Post a Comment