Monday, November 14, 2011

String Matching Algorithms (Naive)


import java.io.*;
public class Naive {
    public static void main(String args[]) throws IOException  {
        System.out.print("\nEnter the Text string : ");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String text = null,pattern = null;
                        text = br.readLine();
            System.out.print("Enter the pattern to be searched : ");
            pattern = br.readLine();
        int n = text.length();
        int m = pattern.length();
        int i = 0;
        for(int s=0;s<=n-m;s++)
        {
            i=0;
                        while(i<m&&text.charAt(s+i) == pattern.charAt(i))
                   i++;
                       if(i==m)
            {
                System.out.println("The pattern "+pattern+" is found at "+(s+1)+"th location");
                return;
            }
        }
        System.out.println("The pattern "+pattern+" is not found in the text :"+text);
    }
}

No comments:

Post a Comment