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