Wednesday, October 2, 2013

BlueJ Program To Merge Two Strings By Taking Alternate Words From Them


In this program, user will enter two sentences which may be of equal or unequal lengths and even the number of words in each sentence may be of unequal numbers. The program is to take alternate words from each string and form a new string. In case any sentence has more number of words then the remaining words will be appended at the end of the modified string.


import java.util.*;
import java.io.*;
class Str
{
 String s1,s2,s3;
 String ss1[],ss2[];
 int m,n;
 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
 StringTokenizer stk,stk1;
 int c1,c2;
 public void takeString()throws Exception
 {
  System.out.println("Enter the first string:");
  s1=br.readLine();
  System.out.println("Enter the second string:");
  s2=br.readLine();
 }
 public void show()
 {
 m=0;
 n=0;
  stk=new StringTokenizer(s1);
  ss1=new String[stk.countTokens()];
  stk1=new StringTokenizer(s2);
  ss2=new String[stk1.countTokens()];
  while(stk.hasMoreTokens())
  {
   ss1[m++]=stk.nextToken();
  }
  while(stk1.hasMoreTokens())
  {
   ss2[n++]=stk1.nextToken();
  }
  s3="";
  c1=0;
  c2=0;
  while(c1< m && c2< n)
  {
   s3=s3+ " "+ss1[c1]+ " "+ ss2[c2];
   c1++;
   c2++;
   }
   if(c1==m)
   {
    while(c2< n)
    {
   s3=s3+ " "+ ss2[c2];
   c2++;
   }
   }
   else
   {
    while(c1< m)
    {
   s3=s3+ " "+ ss1[c1];
   c1++;
   }
   }
   System.out.println("The modified string="+s3);
   }
   public static void main(String args[])throws Exception
   {
   Str ob=new Str();
   ob.takeString();
   ob.show();
   }
   }

Details about the program


Two strings are taken and the strings are converted into tokens using StringTokenizer class. According to the number of tokens in the sentences, two string type array objects are created to store the tokens. Using a while loop, the tokens from alternate arrays are appended in a string object and outside the loop, the remaining tokens are appended.

Sample input and output


Enter the first string: This is a test
Enter the second string: Second string
The modified string= This Second is string a test


No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner