Wednesday, April 13, 2011

BlueJ Program On Eliminating Common Characters From Two Strings


In this BlueJ program user has to enter two strings and the common characters from the strings will be eliminated.

 Codes of the program

import java.io.*;

class Word
{
 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
 String s1,s2,s3="",s4="";
int a[],b[],x=0,y=0;
 int len1,len2;
 char ch;
 int i,j;
  public void take() throws Exception
 {
  System.out.println("Enter the first sentence:");
  s1=br.readLine().trim();
  System.out.println("Enter the second sentence:");
  s2=br.readLine().trim();
  len1=s1.length();
  len2=s2.length();
  a=new int[len1];
  b=new int[len2];
 for(i= 0;i< len1;i++)
 {
  ch=s1.charAt(i);
  for(j=0;j< len2;j++)
  {
   if(ch==s2.charAt(j))
   break;
   }
   if(j!=len2)
   {
   a[x++]=i;
   b[y++]=j;
   }
   }
   for(i=0;i< len1;i++)
   {
    for(j=0;j< x;j++)
    {
     if(i==a[j])
     break;
     }
     if(j==x)
     s3=s3+s1.charAt(i);
    }
   for(i=0;i< len2;i++)
   {
    for(j=0;j< y;j++)
    {
     if(i==b[j])
     break;
     }
     if(j==y)
     s4=s4+s2.charAt(i);
    }
    System.out.println("Original string1="+s1+" Modified string1="+s3);
    System.out.println("Original string2="+s2+" Modified string2="+s4);
  }
  public static void main(String args[]) throws Exception
  {
   Word ob=new Word();
   ob.take();
   }
   }

Technical analysis of this program

In this string modification program, two strings are entered and initially stored in string objects. The first nested loop  loop is used to check for common characters in the strings and the common charater locations are stored in two different arrays. The second nested loop is used to search the common charater locations from the first string and those characters are skipped, remaining characters are appended on another string object. The same process is carried out on the second string object to eliminate the common characters from it. 

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner