Last active
May 20, 2022 05:16
-
-
Save Madhivarman/a4975e3e8e547681a5d5a0da46f77f80 to your computer and use it in GitHub Desktop.
String Pattern matching using BruteForce Algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//brute force algorithm | |
//string matching | |
import java.io.*; | |
import java.util.Scanner; | |
class Bruteforce{ | |
//called function | |
public static int bruteforce(String text,String tobematched){ | |
int length = text.length();//length of the text | |
int plength = tobematched.length();//length of the pattern; | |
//loop condition | |
for(int i=0;i<length-plength;i++){ | |
//initialization of j | |
int j=0; | |
while((j < plength) && (text.charAt(i+j) == tobematched.charAt(j))){ | |
j++; | |
} | |
if(j == plength){ | |
return i; | |
} | |
} | |
return -1; | |
} | |
public static void main(String[] args){ | |
Bruteforce obj = new Bruteforce(); | |
Scanner sc = new Scanner(System.in); | |
//text | |
String text = "I Love Programming and I do Programming"; | |
//word that want to be matched in the text | |
String tobematched = "Programming"; | |
//calling the function | |
int position = obj.bruteforce(text,tobematched); | |
int endindex = position+1; | |
//condition to check whether the pattern is matched are not | |
if(position == -1){ | |
System.out.println("Pattern is not matched in the text"); | |
}else{ | |
System.out.println("Found at position:" + (position+1)); | |
System.out.println("End at the position:" + (endindex + tobematched.length())); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
first for loop should be less than or equals to length-plength