Skip to content

Instantly share code, notes, and snippets.

@terrywang
Created February 17, 2014 02:39
Show Gist options
  • Save terrywang/9043776 to your computer and use it in GitHub Desktop.
Save terrywang/9043776 to your computer and use it in GitHub Desktop.
Java code backup ;-) To Compile: javac Match.java Usage: java Match <pattern> <text>
/**
* The Match class implements Brute Force pattern matching.
*
* @author Terry Wang
* @version 0.2
*/
public class Match {
/** variable to record the position of matching */
private static int position = 0;
/**
* Main method
*
* @param args
*/
public static void main(String[] args) {
// command line arguments check
if (args.length != 2) {
System.out.println("Usage: java Match <pattern> <text>");
System.exit(1);
}
System.out.println("Pattern => " + args[0]);
System.out.println("Text => " + args[1]);
// check if pattern length <= text length
if (args[0].length() > args[1].length()) {
System.out.println("<patten> length should be NO GREATER than <text> length");
System.exit(1);
}
// invoke match method defined below
boolean result = match(args[0], args[1]);
if (result == false)
System.out.println("Pattern NOT found");
else
System.out.println("Pattern found at => " + position + "th character");
}
/**
* Brute Force pattern matching method
*
* @param pattern
* The pattern string
* @param text
* The text string
* @return true if pattern found otherwise false
*/
public static boolean match(String pattern, String text) {
int p = pattern.length(); // p is length of pattern
int t = text.length(); // t is length of text
int j;
for (int i = 0; i <= (t - p); i++) {
j = 0;
while ((j < p) && (text.charAt(i + j) == pattern.charAt(j)))
j++;
if (j == p) {
position = i + 1; // match at position i => (i+1)th char
return true;
}
}
return false; // no match return false
} // end of match()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment