Wednesday , 18 October 2017
Home » Class 10 » Printing the initials of a Name or First letters of each word of a Sentence

Printing the initials of a Name or First letters of each word of a Sentence

Question:

Write a program to accept a sentence and print only the first letter of each word of the sentence in capital letters separated by a full stop.
Example :
INPUT SENTENCE : “This is a cat”
OUTPUT : T.I.A.C.

Solution:

/** The class Initials takes a sentence/name as input and prints it's initials.
* @author : www.javaforschool.com
* @Program Type : BlueJ Program - Java
*/

import java.io.*;
class Initials
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s;
char x;
int l;
System.out.print("Enter any sentence: ");
s=br.readLine();
s=" "+s; //adding a space infront of the inputted sentence or a name
s=s.toUpperCase(); //converting the sentence into Upper Case (Capital Letters)
l=s.length(); //finding the length of the sentence</span>
System.out.print("Output = ");

for(int i=0;i<l;i++)
{
x=s.charAt(i); //taking out one character at a time from the sentence
if(x==' ') //if the character is a space, printing the next Character along with a fullstop
System.out.print(s.charAt(i+1)+".");
}
}
}

Output:

Enter any sentence: Java for school students
Output = J.F.S.S.

Explanation:

In this program we are using the following logic:

● We know that the letters of the initials are characters which come immediately after a blank space.
● Using the above logic, we can extract all the letters of an initial, except the first letter, because there is no space in front of the first word, and hence the logic mentioned above won’t work for the first word of the sentence.
● So, after inputting a sentence, we add a space before it, to fit in the above mentioned logic, in order to extract the First letter of the initials.
● Next we convert the inputted sentence into Upper Case (Capital letters) because, the characters of the Initials are all in Upper Case.
● Then, inside the for loop which runs though the complete length of a sentence, we extract each characters one by one and check whether it is a blank space or not.
● Finally, if the character is a blank space, then we print the character after it along with a full stop.

That’s it ! It was as easy as drinking a cup of coffee. Enjoy !

Check Also

[Question 3] ISC 2017 Computer Practical Paper Solved – Caesar Cipher

Solution of Program 3 of ISC 2017 Computer Science Paper 2 (Practical) Exam. Java program to input a sentence and perform Caesar Cipher (Shift alphabets 13 places ahead)

7 comments

  1. Thanks it is very helpful

  2. it is simplest program to understand

  3. thnx!! heped me LOT

  4. thanks the code helps me

  5. rally helped me a lot !!!

  6. god help me today

Leave a Reply to rouhan rockstar Cancel reply

Your email address will not be published. Required fields are marked *