Hi,
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.
Cheers,
David
(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.
-
String s = “String”;
int counter = 0;
for( int i=0; i<s.length(); i++ ) {
if( s.charAt(i) == ‘Substring’ ) {
counter++;
}
}
-
int count = StringUtils.countMatches(“String”, “SubString”);
Hope that helps.
-Niteesh
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;
while(st.hasMoreTokens())
{
if( st.nextToken().equals(“yourSubString”)){
i++;
}
}
System.out.print("Total no of substring = " + i);