Home » Strings(We Suck Every1) » String Matching

String Matching


import java.util.Scanner;

public class StringMatching1
{
 public static void main(String[] args)
 {
 Scanner in = new Scanner(System.in);

String T, P, cand;
 int pos;

System.out.print("Enter a text string T: ");
 T = in.nextLine();
 System.out.print("Enter a pattern string P: ");
 P = in.next();

 // Complexity : O(n) 1 for loop only...

 for ( pos = 0; pos <= T.length() - P.length(); pos++ )
 {
 cand = T.substring( pos, pos+P.length() ); // Try to match this...

if ( P.equals(cand) )
 {
 System.out.println("Found pattern at posistion: " + pos); // Found
 }
 else
 System.out.println("Pattern Not Found ");

}
 }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: