Print Initials of a given Name in JAVA
Initials of a Name in JAVA
Example : Input : Mahendra Singh Dhoni
Output : M.S. Dhoni
Algorithm and Program 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
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
All the best :)
Arman
ReplyDeleteKar kya rakha Hai yeh.
Ooper likha Hai initials of a name aur neeche likha Hai Arrange the string in alphabetical order