How do I count word occurrences in a string?
Category: Commons Lang, viewed: 1663 time(s).
package org.kodejava.example.commons.lang; import org.apache.commons.lang.StringUtils; public class WordCountExample { public static void main(String[] args) { // We have the source text we'll do the search on. String source = "From the download page, you can download the Java " + "Tutorials for browsing offline. Or you can just download " + "the examples."; // The word we want to count its occurrences String word = "you"; // Using StringUtils.countMatches() method we can count the occurrences // frequency of a word/letter in the giver source of string. int wordFound = StringUtils.countMatches(source, word); // Print how many we have found the word System.out.println(wordFound + " occurrences of the word '" + word + "' was found in the text."); } } |
Here is the result of the code above.
2 occurrences of the word 'you' was found in the text.
Can't find what you are looking for? Join our FORUMS and ask some questions!
Related Examples
- How do I find text between two strings?
- How do I check for an empty string?
- How do I get the nearest hour, minute, second of a date?
- How do I format date and time using DateFormatUtils class?
- How do I find items in an array?
- How do I use CompareToBuilder class?
- How do I use ReflectionToStringBuilder class?
- How do I convert array of object to array of primitive?
- How do I convert an array to a Map?
- How do I reverse array elements order?