|
|
T = acgttagatactaggatgcca
P = gata
Try:
acgttagatactaggatacca
gata
acgttagatactaggatacca
gata
acgttagatactaggatacca
gata
acgttagatactaggatacca
gata
and so on...
|
|
|
0123456789.....
T = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
ppppp
^^^^^
First position that P could be found
So: start looking for P at position: 0
|
0123456789.....
T = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
ppppp
^^^^^
|
Last position that
P could be found
|
T = text;
P = pattern;
for ( pos = 0; pos <= T.length()-P.length(); pos++ ) do
{
if ( P is found starting at position pos )
{
print pos;
}
}
|
T = text;
P = pattern;
for ( pos = 0; pos <= T.length()-P.length(); pos++ ) do
{
cand = T.substring( pos, pos+P.length() ); // Try to match this...
if ( P equal to cand )
{
print pos;
}
}
|
|
String1.equals( String2 )
returns: true if String1 and String2 contains the same characters
in the same order
false otherwise
|
if ( P.equals(cand) )
{
....
}
|
Scanner input = new Scanner( System.in );
String s;
s = input.next(); // Read a word (ended by a space)
|
|
Scanner input = new Scanner( System.in );
String s;
s = input.nextLine(); // Read a line (ended by RETURN)
|
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();
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
}
}
}
}
|
How to run the program:
|
UNIX>> java StringMatching1 Enter a text string T: acgttagatactaggatacca Enter a pattern string P: gata 6 14 |
import java.util.Scanner;
public class StringMatching2
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String T, P, cand;
int pos, i;
System.out.print("Enter a text string T: ");
T = in.nextLine();
System.out.print("Enter a pattern string P: ");
P = in.next();
System.out.println();
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(T); // Print the text
for ( i = 0 ; i < pos; i++ ) // Indent to found position
System.out.print(" ");
System.out.println(P); // Print the pattern below
System.out.println();
}
}
}
}
|
How to run the program:
|
Sample output:
UNIX>> java StringMatching2 Enter a text string T: acgttagatactaggatacca Enter a pattern string P: gata acgttagatactaggatacca gata acgttagatactaggatacca gata |