Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,945 questions

51,887 answers

573 users

How to find occurrences of a substring in a string in Java

3 Answers

0 votes
public class MyClass
{
    public static boolean isEmpty(String s) {
        return s == null || s.length() == 0;
    }
 
    public static int GetOccurrences(String str, String sub) {
        if (isEmpty(str) || isEmpty(sub)) {
            return 0;
        }
 
        return str.split(sub, -1).length - 1;
    }
 
    public static void main(String[] args)
    {
        String str = "DDEEAABCAEEEFDDAAEFFEEEEBA";
        String sub = "EE";
 
        int count = GetOccurrences(str, sub);
        
        System.out.println(count);
    }
}




/*
run:

4

*/

 



answered Mar 18, 2023 by avibootz
0 votes
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MyClass
{
    public static boolean isEmpty(String s) {
        return s == null || s.length() == 0;
    }
 
    public static int GetOccurrences(String str, String sub) {
        if (isEmpty(str) || isEmpty(sub)) {
            return 0;
        }
 
        Matcher matcher = Pattern.compile(sub).matcher(str);
 
        int count = 0;
        while (matcher.find()) {
            count++;
        }
 
        return count;
    }
 
    public static void main(String[] args)
    {
        String str = "DDEEAABCAEEEFDDAAEFFEEEEBA";
        String sub = "EE";
 
        int count = GetOccurrences(str, sub);
        
        System.out.println(count);
    }
}




/*
run:

4

*/

 



answered Mar 18, 2023 by avibootz
0 votes
public class MyClass
{
    public static boolean isEmpty(String s) {
        return s == null || s.length() == 0;
    }
 
    public static int GetOccurrences(String str, String sub) {
        if (isEmpty(str) || isEmpty(sub)) {
            return 0;
        }
 
        return (str.length() - str.replace(sub, "").length()) / sub.length();
    }
 
    public static void main(String[] args)
    {
        String str = "DDEEAABCAEEEFDDAAEFFEEEEBA";
        String sub = "EE";
 
        int count = GetOccurrences(str, sub);
        
        System.out.println(count);
    }
}




/*
run:

4

*/

 



answered Mar 18, 2023 by avibootz
...