Saturday, 18 June 2016

Program to print the Words of a Given String ending with a Particular Letter.

Explanation :
If String= "All cars are supercars until they have tires".
1)If Letter = "s" then output will be "cars,supercars,tires".
2)If Letter = "l" then output will be "All,until".
3)If letter = "v" then output will be "There are no words ending with Letter v".

Code:

import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;
public class EndsWithLetter
{   
     public static void main(String args[])
     {
        int count=0;
        ArrayList<String> ar= new ArrayList<String>();
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter any String");
        String x=sc.nextLine();
        System.out.println("Enter a letter");
        String y=sc.nextLine();
        StringTokenizer st=new StringTokenizer(x,",/-@ ");
        while(st.hasMoreTokens())
        {
            String st1 = (String) st.nextToken();
            if(st1.endsWith(y))
            {
                ar.add(st1);//Adding Words in ArrayList
                count+=1;
            }
        }
        if(count!=0)
        {
                System.out.println("Words ending with letter "+y+" are:");
                for(String z:ar)
                {
                    System.out.println(z);
                }
        }
        else System.out.println("There are no words ending with Letter "+y);
        sc.close();
    }
}

No comments:

Post a Comment