Program to Implement K-Naive Algorithm in Java

import java.io.*;
class bf_fun {
    int bf(String t, String p) {
        int n = t.length();
        int m = p.length();
        int j = 0, flag = 0;

        for (int i = 0; i <= n - m; i++) {
            if (p.charAt(j) == t.charAt(i)) {
                if (m == 1)
                    return i + 1;
                for (int k = 1; k < m; k++) {
                    if (p.charAt(j + k) == t.charAt(i + k))
                        flag = k + 1;
                }
                if (flag == m)
                    return i + 1;
            }
        }
        return -1;
    }
}

class bf1 {
    public static void main(String args[]) throws IOException {
        InputStreamReader input = new InputStreamReader(System.in);
        BufferedReader obj = new BufferedReader(input);
        System.out.println("Enter the string");
        String s = obj.readLine();
        System.out.println("Enter the substring");
        String ts = obj.readLine();
        bf_fun f = new bf_fun();
        int n = f.bf(s, ts);
        if (n != -1)
            System.out.println("Pattern matched as position: " + n);
        else
            System.out.println("No pattern matching");
    }
}


/* 

output

Enter the string

what is your name
Enter the substring

is
Pattern matched as position: 6

Process Exit...

*/

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.