ArrayList - String operations


/*
     Write a program to perform string operations using Array List.
     Write functions for the following
          Append - add at end
          Insert – add at particular index
          Search
          List all string starts with given letter
*/

// ArrayList

import java.util.*;

class ArrList
{
     public static void main(String as[])
     {
          ArrayList <String>AL = new ArrayList<String>();
          Scanner s = new Scanner(System.in);
         
          while(true)
          {
              System.out.println("\n1 - Append \t2 - Insert \t3 - Search \t4 - List \t5 - exit");
             
              int ch;
              System.out.print("Enter choice : "); 
              ch = s.nextInt();

              if(ch==1)
              {
                   System.out.print("Enter data : ");
                   String str = s.next();
                  
                   AL.add(str);
              }
              else if(ch==2)
              {
                   System.out.print("Enter position : ");
                   int pos = s.nextInt();
                   System.out.print("Enter data : ");
                   String str = s.next();
                   AL.add(pos,str);
              }
              else if(ch==3)
              {
                   int i;
                   System.out.print("Enter data to search : ");
                   String str = s.next();
                  
                   String str_arr[] = new String[AL.size()];
                   str_arr = AL.toArray(str_arr);             
                  
                   for(i=0;i<AL.size();i++)
                        if(str.equalsIgnoreCase(str_arr[i]))
                        {
                             System.out.println("String "+str+" found at position "+(i+1));
                             break;
                        }
                   if(i==AL.size())
                        System.out.println("String not found.");
              }
              else if(ch==4)
              {
                   System.out.println("Elements in ArrayList are : "+AL);
                  
                   int i;
                   System.out.print("Enter starting character : ");
                   char c = (s.next()).charAt(0);
                  
                  
                   String str_arr[] = new String[AL.size()];
                   str_arr = AL.toArray(str_arr);             
                   System.out.println("String atarting with character "+c+" are : ");
                   for(i=0;i<AL.size();i++)
                        if(str_arr[i].charAt(0)==c)
                             System.out.println(str_arr[i]);
              }
              else if(ch==5)
                   System.exit(0);
              else
                   System.out.println("Invalid choice");
          }
     }
}

No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu