Thursday, 6 September 2012

java program to find string matching in another string.


import java.io.*;

class paturn_match
{
       public static void main(String args[]) throws IOException
       {
             BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
             char test[] = new char[100];
             char given_str[] = new char[15];
             String temp;
             int i,j,lentext,lenp,flag=0,count=0;
         
             System.out.print("Enter Text  =  ");
             temp = br.readLine();
             test = temp.toCharArray();
             lentext = temp.length();
         
             System.out.print("Enter Paturn  =  ");
             temp = br.readLine();
             given_str = temp.toCharArray();
             lenp = temp.length();

             for(i=0;i!=lentext-1;i++)
             {
                   j=i;
                   int k=0;
                   flag=0;
                         while((test[i] == given_str[k]) && (flag !=1))
                         {
                               j=j+1;
                               k=k+1;
                                    if(k>=(lenp-1))
                                    {
                                          flag=1;
                                          break;
                                    }
                         } //WHILE
                     
                         if((k>0) && (flag==1))
                         {
                               System.out.println(" Paturn found at  " + i);
                               count++;
                         }
            }  // FOR LOOP
        
            System.out.println(" count = " + count);
    }
} //paturn_match.java

output:


Enter Text  =  hello hello
Enter Paturn  =  he
 Paturn found at  0
 Paturn found at  6
 count = 2