Pattern searching in a String - Java Program

    Patterns are some sequences of characters. Let us consider this as String. This program is developed in java. To search the pattern in the string, it follows a user defined function.

Program Logic:

  • A string and a pattern are given as input.
  • Both of the input’s length is found and assigned to variables.
  • Using these two length, two “for loops” are written and check each character in the two inputs.
  • When the input string meets the pattern, it stops.
  • Otherwise, it repeats the process until the last character.

Steps to develop the program:

  • Include the built in package java.util.Scanner.
  • A public class PatternSearchingPgm is written with main() class.
  • It uses the above logic in search () function.
  • Inside the main() function,two  objects are created for Scanner class.
  • These two objects read the input string and pattern.
  • Call the search() function with these two inputs.
  • Print the output.

Program:

import java.util.Scanner;

public class PatternSearchingPgm {

    public static void search(String iotext, String pattern1) {

        int textLength = iotext.length();

        int patternLen = pattern1.length();

        //for loops to search the pattern in the String

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

            int j;

            for (j = 0; j < patternLen; j++) {

                if (iotext.charAt(i + j) != pattern1.charAt(j)) {

                    break;

                }

            }

             if (j == patternLen) {

                System.out.println("Yes. The Pattern is found at index " + i);

            }

        }

    }

    public static void main(String[] args) {

       //myObj1,myObj2 are created to read the input String and pattern from the user.

        Scanner myObj1 = new Scanner(System.in);

        System.out.println("Enter the String");

        String iotext = myObj1.nextLine();

        Scanner myObj2 = new Scanner(System.in);

        System.out.println("Enter the pattern");

        String pattern1 = myObj2.nextLine();

        //Function call

        search(iotext, pattern1);

    }

}

Output:

C:\raji\blog>javac PatternSearchingPgm.java

C:\raji\blog>java PatternSearchingPgm

Enter the String

Java World Welcomes You!!!

Enter the pattern

World

Yes. The Pattern is found at index 5

This is the simple way of creating pattern searching program in java. Happy Coding!!!

No comments:

Post a Comment