Blogs

Java – Naive String Search Pattern Matching Algorithm
Author:Dixanta Bahadur Shrestha

String Search and Pattern Matching is one of the import part of computer science. There are various String Searching and Pattern Matching Algorithm are available in the internet. “Naive String Search Pattern Matching Algorithm" one of them and its easy to write and test.

I have written a small script in Java in order to accomplish String Searching and Pattern Matching as simple as possible.

Examples:

Input:
text="this is input text";
pattern="text";

Output:
Total Matched Strings: 1
-----------------------------------------------------------------------------
Input:
text="thisthisthisthisthis";
pattern="thisthis";
Output:
Total Matched Strings: 2

Example Code in Java:


package com.cibt;
public class NaiveStringSearch{

    public static void main(String[] args){

        String text="thisthisthisthisthis";

        String pattern="thisthis";

        int textLength=text.length();

        int patternLength=pattern.length();

        int matched=0;

        for(int i=0;i<=(textLength-patternLength);i++){

            int counter=0;

            for(int j=0;j<patternLength;j++){

                int pos=i+j;

                if(text.charAt(pos)==pattern.charAt(j)){

                    counter++;

                    }

                    if(counter==patternLength){

                        matched++;

                        i=pos;

                    }

            }

        }
            
        System.out.println("Total Matched Strings:" + matched);

    }

}
Output:
Total Matched Strings: 2
Happy Coding !!!

Previous