Java: counting how many times a string is repeated

Recently I needed to find a simple way to count how many times a specific keyword is repeated inside a large text. A regular expression would be possible but (besides the complication), it is very slow on large text files (>60 000 lines).

The solution, a very simple code that is crude but works with good enough performance:
int counter = (text.length() - text.replace(keyword, "").length()) / keyword.length();

Not intensively tested but functional.

Hope it helps you.

No comments:

Post a Comment