countMatches method from org.apache.commons.lang3.StringUtils is typically used to count occurrences of a substring or character in a String:
import org.apache.commons.lang3.StringUtils; String newPhrase = "Some words here, some words there, some more words everywhere"; String stringTarget = "words"; int stringOccurrences = StringUtils.countMatches(newPhrase, stringTarget); // 3 char newCharTarget = 'e'; int charOccurrences = StringUtils.countMatches(newPhrase, newCharTarget); // 6
Otherwise for does the same with standard Java API's you could use Regular Expressions:
import java.util.regex.Matcher; import java.util.regex.Pattern; String newText = "New string, more strings, and even more strings!"; System.out.println(countOccurrences("string", newText)); // prints 3 System.out.println(countOccurrences("more", newText)); // prints 2 public static int countOccurrences(String searchTerm, String newText) { Pattern pattern = Pattern.compile(searchTerm); Matcher matcher = pattern.matcher(newText); int occurrences = 0; while (matcher.find()) { occurrences++; } return occurrences; }
This code snippet is a Java program that counts the occurrences of a specified search term within a given text using regular expressions (java.util.regex). Here's an explanation:
Import Statements:
Variables:
Method Invocation:
Method countOccurrences():
The method essentially uses the Pattern and Matcher classes to find and count occurrences of the specified search term within the given text using regular expressions.
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions