Initials of a Name in JAVA
In this program we will input a name from the user and print its initials.
Example : Input : Mahendra Singh Dhoni
Output : M.S. Dhoni
Algorithm and Program given below :-
Algorithm :-
Input a name in a variable
Than add a blank space before the it
Find the length of the name in a variable
Now find the last blank space index in a new variable
Store the part of the string from last blank space in a new variable
Start a for loop till last index of blank space
Extract the characters from the string.
If blank space is found than add the next character after the space and add (.)
Add both this and string with last part of the string
Print the Result.
Program :-
import java.io.*; import java.util.*; class Initial_Name { public static void main(String args[]) { Scanner in = new Scanner(System.in); String str,str1="",str2=""; char ch,ch1; int l,p,i; System.out.print("Enter Word : "); str=in.nextLine(); str=" "+str; l= str.length(); p= str.lastIndexOf(" "); // find the index of last blank space str2= str.substring(p+1); // Storing the Last part of the string for(i=0;i<p;i++) { ch=str.charAt(i); if(ch==' ') { str1=str1+str.charAt(i+1)+"."; // Storing Initials } } str2=str1+str2; // Adding initials and Surname System.out.println("Original Name : "+str); System.out.println("Initial Name : "+str2); } // end of main } // end of class
Note : The program is written in the easiest way possible so try understand it. If you face any problem in understanding this program than feel free to contact/comment.
All the Best :)
Keep Learning :)
Comments