Count function in Java

I’m not really crash hot in Java and am wondering if someone would be willing to share their knowledge with me. I need a Java service that counts the number of times a certain “sub-string” occurs in a given string. I’ve gotten a basics of it worked out in a flow service, but, it’s not pretty. I’m thinking that the performance would be better in a Java Service invoked from Flow code.

(I got into webMethods via the backdoor, I have 20+ years experience with COBOL/CICS/DB2)…

Hi David,

This can be done in many ways. But i prefer below methods and one using apache library.

  1. String s = “String”;
    int counter = 0;
    for( int i=0; i<s.length(); i++ ) {
    if( s.charAt(i) == ‘Substring’ ) {

  2. int count = StringUtils.countMatches(“String”, “SubString”);

Hope that helps.


Hi David,
Try below.

String testString = “some string”;
StringTokenizer st = new StrngTokenizer(testString, String delim) /* delimeter could be white space so it can be mentioned as " ") */

int i = 0;
if( st.nextToken().equals(“yourSubString”)){
System.out.print("Total no of substring = " + i);