Java Program to Perform String Matching Using String Library

This is a java program to perform search using string library.

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

  1.  
  2. package com.sanfoundry.setandstring;
  3.  
  4. import java.util.Scanner;
  5.  
  6. public class StringSearchUsingStrLib
  7. {
  8.     public static void main(String[] args)
  9.     {
  10.         Scanner sc = new Scanner(System.in);
  11.         System.out.println("Enter the main string: ");
  12.         String text = sc.nextLine();
  13.         System.out.println("Enter the pattern string: ");
  14.         String pattern = sc.nextLine();
  15.         for (int i = 0; i <= (text.length() - pattern.length()); i++)
  16.         {
  17.             if (text.substring(i, (i + pattern.length())).equalsIgnoreCase(
  18.                     pattern))
  19.             {
  20.                 System.out.println(pattern
  21.                         + " is substring of main string, match found at: "
  22.                         + ++i);
  23.             }
  24.         }
  25.         sc.close();
  26.     }
  27. }

Output:

$ javac StringSearchUsingStrLib.java
$ java StringSearchUsingStrLib
 
Enter the main string: 
Java Program to Perform String Matching Using String Library
Enter the pattern string: 
String
String is substring of main string, match found at: 25
String is substring of main string, match found at: 47

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement

Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.