• Register
+2 votes
9 views

Problem:

Hello guys,

I hope you all are doing well. I am learning java programming in my school. My teacher taught us many things about the string in the last class and gave a problem to solve. I tried to solve the problem but couldn’t make it happen so far. I found this website very helpful and friendly. If anybody could help me to solve this problem I’d be grateful to him/her.

So, my problem is: find all occurrences of a substring in a string java

Thanks, mate.

ago by (6k points)  

1 Answer

+1 vote

Solution:

Finding the substring from a string is an interesting thing to do. There are two ways to do it, one is Naive pattern searching another one is KMP algorithm

I think the first one is pretty easier for the beginners. So, let’s practice with the Naive pattern searching: 

public class SubString { 
      
    static int countFreq(String pat, String txt) {         
        int i = pat.length();         
        int j = txt.length();         
        int res = 0; 
        for (int m = 0; m <= i - j; m++) { 
            int n;             
            for (n = 0; n < i; n++) { 
                if (txt.charAt(m + n) != pat.charAt(n)) { 
                    break; 
                } 
            } 
            if (n == i) {                 
                res++;                 
                n = 0;                 
            }             
        }         
        return res;         
    } 
  
    static public void main(String[] args) { 
        String txt = "naymulhasan";         
        String pat = "san";         
        System.out.println(countFreq(pat, txt));         
    } 
} 

To know more about string algorithms click here

ago by (17.9k points)  
...