Dremendo Tag Line

Input a sentence and print those words which begins and ends with same alphabet in Java

String - Question 6

In this question, we will see how to input a sentence and print those words which begins and ends with same alphabet in Java programming. To know more about string click on the string lesson.

Q6) Write a program in Java to input a sentence and print those words which begins and ends with same alphabet.

Program

import java.util.Scanner;

public class Q6
{
    public static void main(String args[])
    {
        String s,w="";
        char fc,lc;
        int i;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a sentence");
        s=sc.nextLine()+" ";

        for(i=0; i<s.length(); i++)
        {
            if(s.charAt(i)!=' ')
            {
                //concatenates the character until we find a space
                w=w+s.charAt(i);
            }
            else
            {
                // first character
                fc=Character.toLowerCase(w.charAt(0));

                // last character
                lc=Character.toLowerCase(w.charAt(w.length()-1));

                if(fc==lc)
                {
                    System.out.println(w);
                }
                w="";
            }
        }
    }
}

Output

Enter a sentence
My mom and dad love me so much
mom
dad
video-poster