Despite my distaste for Java, I work in it every day at e-kiwi (author of software Screen-Scraper).
As usual, I was surprised to find that Java has no easy way to count the number of occurances of a substring within a given String variable. I Google’d it and was surprised at the first result’s poor coding. It had a ‘while (true)‘ loop with a goofy break statement tied to a misleadingly-named variable.
public int countIndexOf(String text, String search)
int count = 0;
for (int fromIndex = 0; fromIndex > -1; count++)
fromIndex = text.indexOf(search, fromIndex + ((count > 0) ? 1 : 0));
return count - 1;
Pardon the ternary operator in there, but Java doesn’t like making boolean-casting-to-int easy.
If there are any errors you encounter, just let me know and I’ll fix it. My use for such a function doesn’t require the ‘border’ cases where substrings are at the beginning or end of the main string. If you know that you don’t need to match a substring which will begin at the first character of the main string, you can change the ternary part from:
fromIndex + ((count > 0) ? 1 : 0)
fromIndex + 1
Sorry to the dude that I flamed on his blog, but poorly written code is easy to find these days. Idioms are the way to go. Java’s slow enough as an interpretted language that it doesn’t need extraneous if-else statements in ‘while (true)’ loops and incessant variable assignment to immutable values.
You might argue that it doesn’t really matter if you lose a few cycles on today’s machines, but programs should be as efficient as possible when it’s worth the time. You may as well take a few minutes (or even an hour) and figure out the best way to do something. Forethought with save you an amazing amount of time in the future when you develope real programs and not just school assignments.