Java Program to Perform Naive String Matching

This is a java program to perform Naive String matching algorithm.

Here is the source code of the Java Program to Perform Naive String Matching. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

package com.maixuanviet.setandstring;
 
import java.util.Scanner;
 
public class StringSearchUsingNaiveMethod
{
    private final int BASE;
    private int[]     occurrence;
    private String    pattern;
 
    public StringSearchUsingNaiveMethod(String pattern)
    {
        this.BASE = 256;
        this.pattern = pattern;
        occurrence = new int[BASE];
        for (int c = 0; c < BASE; c++)
            occurrence = -1;
        for (int j = 0; j < pattern.length(); j++)
            occurrence[pattern.charAt(j)] = j;
    }
 
    public int search(String text)
    {
        int n = text.length();
        int m = pattern.length();
        int skip;
        for (int i = 0; i <= n - m; i += skip)
        {
            skip = 0;
            for (int j = m - 1; j >= 0; j--)
            {
                if (pattern.charAt(j) != text.charAt(i + j))
                {
                    skip = Math.max(1, j - occurrence[text.charAt(i + j)]);
                    break;
                }
            }
            if (skip == 0)
                return i;
        }
        return n;
    }
 
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the main string: ");
        String text = sc.nextLine();
        System.out.print("Enter the string to be searched: ");
        String pattern = sc.nextLine();
        StringSearchUsingNaiveMethod nsm = new StringSearchUsingNaiveMethod(
                pattern);
        int first_occur_position = nsm.search(text);
        System.out.println("The text '" + pattern
                + "' is first found after the " + first_occur_position
                + " position.");
        sc.close();
    }
}

Output:

$ javac StringSearchUsingNaiveMethod.java
$ java StringSearchUsingNaiveMethod
 
Enter the main string: Sanfoundry is No. 1 choice for Deep Hands-ON Trainings in SAN, Linux & C, Kernel & Device Driver Programming. Our Founder has trained employees of almost all Top Companies in India. Here are few of them: VMware, Citrix, Oracle, Motorola, Ericsson, Aricent, HP, Intuit, Microsoft, Cisco, SAP Labs, Siemens, Symantec, Redhat, Chelsio, Cavium Networks, ST Microelectronics, Samsung, LG-Soft, Wipro, TCS, HCL, IBM, Accenture, HSBC, Northwest Bank, Mphasis, Tata Elxsi, Tata Communications, Mindtree, Cognizant, mid size IT companies and many Startups. Students from top Universities and colleges such as NIT Trichy, BITS Pilani, University of California, Irvine, University of Texas, Austin & PESIT Bangalore have benefited a lot from these courses as well. The assignments and real time projects for our courses are of extremely high quality with excellent learning curve.
Enter the string to be searched: No. 1 
The text 'No. 1 ' is first found after the 14 position.

Related posts:

Sắp xếp trong Java 8
Hướng dẫn Java Design Pattern – Iterator
Java Program to Find Inverse of a Matrix
Spring Security with Maven
Java Program to Check Whether an Undirected Graph Contains a Eulerian Cycle
Spring REST API + OAuth2 + Angular (using the Spring Security OAuth legacy stack)
Giới thiệu java.io.tmpdir
Adding a Newline Character to a String in Java
Java Program to Solve Tower of Hanoi Problem using Stacks
Spring Boot - Batch Service
Java Program to find the peak element of an array using Binary Search approach
Java Program to Construct an Expression Tree for an Infix Expression
Derived Query Methods in Spring Data JPA Repositories
Spring Boot - Cloud Configuration Client
Java Program to Find Maximum Element in an Array using Binary Search
Quick Guide to the Java StringTokenizer
Spring Boot - Securing Web Applications
The DAO with Spring and Hibernate
Java – InputStream to Reader
Spring Security Registration – Resend Verification Email
Java Program to find the number of occurrences of a given number using Binary Search approach
Easy Ways to Write a Java InputStream to an OutputStream
How to Manually Authenticate User with Spring Security
Java Program to Compute the Area of a Triangle Using Determinants
Java Program to Perform Matrix Multiplication
Java Program to Find the Shortest Path Between Two Vertices Using Dijkstra’s Algorithm
Java Program to Describe the Representation of Graph using Incidence Matrix
Java Program to Construct an Expression Tree for an Prefix Expression
Spring Security Custom AuthenticationFailureHandler
ClassNotFoundException vs NoClassDefFoundError
Java Program to Check whether Undirected Graph is Connected using DFS
Jackson – Decide What Fields Get Serialized/Deserialized