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
advertisement

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

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest 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
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.