Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class NaivePatternMatching {
- /**
- * @param args the command line arguments
- */
- public static int search(String txt, String pat)
- {
- int M = pat.length();
- int N = txt.length();
- int index = -1;
- /* A loop to slide pat one by one */
- for (int i = 0; i <= N - M; i++) {
- int j;
- /* For current index i, check for pattern
- match */
- for (j = 0; j < M; j++) {
- if (txt.charAt(i + j) != pat.charAt(j))
- break;
- }
- if (j == M) // if pat[0...M-1] = txt[i, i+1, ...i+M-1]
- index = i;
- }
- return index;
- }
- public static void main(String[] args) {
- // TODO code application logic here
- Scanner sc = new Scanner(System.in);
- String txt;
- String pat;
- System.out.println("Enter the main string: ");
- txt = sc.nextLine();
- System.out.println("Enter the pattern/finding string: ");
- pat = sc.nextLine();
- int ans = search(txt, pat);
- if(ans==-1)System.out.println("Pattern not found!!");
- else System.out.println("Pattern found at position "+ans+1);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement