How to count how many times a substring appears in a String in Java?

To count how many times a substring appears in a String in Java, call indexOf in a while loop.

Here's how you do it:

String string = "Hello World!";
String substring = "l";
int count = 0;
int lastIndex = 0;

while (true) {
  lastIndex = string.indexOf(substring, lastIndex);

  if (lastIndex < 0) {
    break;
  } else {
    count++;
    lastIndex++;
  }
}

System.out.println(count); // 3