Java program to print the initial letters of the words present in the String

(135 Views)


This Java program accepts a String from the user and then prints a new String containing the initial letters of the words present in the String which is separated by a dot(.) For Example -
Input: We love Java
Output: W.l.J.

import java.util.Scanner; class PrintInitialLetter { public static void main(String[] args) { String s; System.out.println("Enter String"); Scanner sc=new Scanner(System.in); s=sc.nextLine(); s=" "+s; //add whitespace before first word int l=s.length(); String ans=""; char c='n'; int i; for(i=0;i<l;i++) { c=s.charAt(i); if(c==' ') // check if character is a whitespace { ans=ans+s.charAt(i+1)+"."; } } System.out.println("The final String: "+ans); } }

Output:

Enter String I love Java The final String: I.l.J.

Solution Worked 3 UpvotesUpvote

        

Solution Didn't Worked 0 DownvotesDownvote



Comments



Search