Times a substring appears in a string

I want to know the number of times a particular substring appears in a particular string. For example:

    String s = "acbdsfjabcsdfdabc";

The result I want is to know how many times "abc" appears using a scanner to input the mentioned string and using a counter in loop to count the number of thimes the string appears..

1 answer

  • answered 2018-07-11 04:17 Chris H

    Try this

    String sub = "abc";
    String s = "acbdsfjabcsdfdabc";
    int count = 0;
    for (int i = 0; i < s.length(); i++) {
           if (s.substring(i, i+3).equals(sub)) {
    return count;