Java Data Type How to - Find how many times does a string object repeat








Question

We would like to know how to find how many times does a string object repeat.

Answer

import java.util.regex.Matcher;
import java.util.regex.Pattern;
//from  ww  w  .j a v a 2s . c  o  m
public class Main {
  public static void main(String[] args) {
    String hello = "HelloxxxHelloxxxHello"; // String you want to 'examine'
    Pattern pattern = Pattern.compile("Hello"); // Pattern string you want to be
                                                // matched
    Matcher matcher = pattern.matcher(hello);

    int count = 0;
    while (matcher.find()) {
      count++; // count any matched pattern
    }
    System.out.println(count);
  }
}